0

JAXB trên Java 7

JAXB là một công nghệ trong J2EE trong lịch sử, rồi sau đó là Java EE, và hiện tại là Jakarta EE. Bài viết giới thiệu các bạn ánh xạ Java object và XML. Việc sử dụng JAXB thường dùng trong thao tác với Java webserivce. Chuẩn bị JDK 7 hoặc JDK 8. Mã nguồn để ở Java language level 7.

File pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.github.donhuvy</groupId>
    <artifactId>sample_jaxb_java7</artifactId>
    <version>1.0.0</version>
    <name>sample_jaxb_java7</name>
    <url>https://github.com/donhuvy/sample_jaxb_java7</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.7.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-project-info-reports-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

Đối tượng Phòng ban, thể hiện qua class Department.java

package org.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement(namespace = "http://example.com/jaxb")
@XmlAccessorType(XmlAccessType.FIELD)
public class Department {

    private String deptNo;
    private String deptName;
    private String location;

    @XmlElementWrapper(name = "employees")
    @XmlElement(name = "employee")
    private List<Employee> employees;

    /**
     * This default constructor is required if there are other constructors.
     */
    public Department() {

    }

    public Department(String deptNo, String deptName, String location) {
        this.deptNo = deptNo;
        this.deptName = deptName;
    }

    public String getDeptNo() {
        return deptNo;
    }

    public void setDeptNo(String deptNo) {
        this.deptNo = deptNo;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }

}

Đối tượng Nhân viên, thể hiện qua đối tượng Employee.java

package org.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {

    private String empNo;
    private String empName;
    private String managerNo;

    /**
     * Must have empty constructor.
     */
    public Employee() {

    }

    public Employee(String empNo, String empName, String managerNo) {
        this.empNo = empNo;
        this.empName = empName;
        this.managerNo = managerNo;
    }

    public String getEmpNo() {
        return empNo;
    }

    public void setEmpNo(String empNo) {
        this.empNo = empNo;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getManagerNo() {
        return managerNo;
    }

    public void setManager(String managerNo) {
        this.managerNo = managerNo;
    }

}

File chạy để xem kết quả App.java

package org.example;

import org.model.Department;
import org.model.Employee;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Hello world!
 */
public class App {

    private static final String XML_FILE = "departments.xml";

    public static void main(String[] args) {
        Employee emp1 = new Employee("20160922", "Nguyen Bich Van", null);
        Employee emp2 = new Employee("20150724", "Nguyen Viet Hung", "20160922");
        Employee emp3 = new Employee("20140821", "Nguyen Tien Nam", null);
        List<Employee> employees = new ArrayList<Employee>();
        employees.add(emp1);
        employees.add(emp2);
        employees.add(emp3);
        Department department = new Department("SALES", "ACCOUNTING", "HANOI");
        department.setEmployees(employees);
        try {
            JAXBContext context = JAXBContext.newInstance(Department.class);

            // Marshalling from Java object to file.
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(department, System.out);
            File file = new File(XML_FILE);
            // Write to file.
            marshaller.marshal(department, file);

            // Write to console screen.
            System.out.println("Write to file: " + file.getAbsolutePath());

            // Unmarshalling from file to console screen.
            Unmarshaller unmarshaller = context.createUnmarshaller();
            Department deptFromFile = (Department) unmarshaller.unmarshal(new FileReader(XML_FILE));
            List<Employee> employeeList = deptFromFile.getEmployees();
            // Print to console screen.
            for (Employee employee : employeeList) {
                System.out.println("Employee: " + employee.getEmpName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// Result:

// <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
// <ns2:department xmlns:ns2="http://example.com/jaxb">
// <deptNo>SALES</deptNo>
// <deptName>ACCOUNTING</deptName>
// <employees>
// <employee>
// <empNo>20160922</empNo>
// <empName>Nguyen Bich Van</empName>
// </employee>
// <employee>
// <empNo>20150724</empNo>
// <empName>Nguyen Viet Hung</empName>
// <managerNo>20160922</managerNo>
// </employee>
// <employee>
// <empNo>20140821</empNo>
// <empName>Nguyen Tien Nam</empName>
// </employee>
// </employees>
// </ns2:department>
//        Write to file: E:\github\sample_jaxb_java7\departments.xml
//        Employee: Nguyen Bich Van
//        Employee: Nguyen Viet Hung
//        Employee: Nguyen Tien Nam
//        Disconnected from the target VM, address: '127.0.0.1:51287', transport: 'socket'
//
//        Process finished with exit code 0

File XML có tên departments.xml sinh ra sau khi marshalling từ Java object:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:department xmlns:ns2="http://example.com/jaxb">
    <deptNo>SALES</deptNo>
    <deptName>ACCOUNTING</deptName>
    <employees>
        <employee>
            <empNo>20160922</empNo>
            <empName>Nguyen Bich Van</empName>
        </employee>
        <employee>
            <empNo>20150724</empNo>
            <empName>Nguyen Viet Hung</empName>
            <managerNo>20160922</managerNo>
        </employee>
        <employee>
            <empNo>20140821</empNo>
            <empName>Nguyen Tien Nam</empName>
        </employee>
    </employees>
</ns2:department>

Mã nguồn: https://github.com/donhuvy/sample_jaxb_java7


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.