将 JPA 对象转换为 XML / JAXB



我想将数据从表转换为XML文件。数据采用以下格式

    Continent   Country     County      Town
    --------------------------------------------------------------
    Africa      Kenya       South       Mombasa
    Africa      Egypt       South       Cairo
    Europe      England     North       Birmingham
    Asia        Japan       South       Tokyo

将生成的 XML 文档类似于如下所示的文档:

<continents>
    <continent name="Africa">
        <countries>
            <country>
                <countryName>Kenya</countryName>
                <county>South</county>
                <town>Mombasa</town>
            </country>
            <country>
                <countryName>Egypt</countryName>
                <county>South</county>
                <town>Cairo</town>
            </country>
        </countries>
    </continent>
    <continent name="Europe">
        <countries>
            <country>
                <countryName>England</countryName>
                <county>North</county>
                <town>Birminghan</town>
            </country>
        </countries>
    </continent>
    <continent name="Asia">
        <countries>
            <country>
                <countryName>Japan</countryName>
                <county>South</county>
                <town>Tokyo</town>
            </country>
        </countries>
    </continent>    
</continents>

我计划做的是将数据从数据库读入 JPA 对象。这将返回以下对象的列表

@Entity
@Indexed
@Table(name="TOWN")
public class Town {
    protected String continent;
    protected String country;
    protected String county;
    protected String town;
    @Id 
    @Column(name="CONTINENT")
    public String getContinent() {
        return continent;
    }
    public void setContinent(String continent) {
        this.continent = continent;
    }
    @Column(name="COUNTRY")
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    @Column(name="COUNTY")
    public String getCounty() {
        return county;
    }
    public void setCounty(String county) {
        this.county = county;
    }
    @Column(name="TOWN")
    public String getTown() {
        return town;
    }
    public void setTown(String town) {
        this.town = town;
    }   
}

当我运行调用以从数据库中检索行时,我将获得以下格式的列表:

List<Town> towns = entityManager.getAllTowns();

为了能够生成XML文件,我必须迭代列表并处理每个"Town"对象。我可以使用 DOM,但我觉得会有很多 for 循环和 if 语句能够生成 XML 文档。是否可以生成 XML 文档,而不必循环访问列表来构建上面显示的 xml 文件?

我已经将 JPA 对象转换为 Jaxb,但这是一种一对一映射的平面关系(即 XML 结构中没有子元素或内部元素)。我不明白如何执行示例 xml 文件所需的子元素和条件规则。

我在Spring 3中使用JPA/Hibernate。是否可以生成示例 xml 文件,或者由于 XML 文件的格式,我是否需要手动执行(使用 for 循环和 if 语句)?

谢谢

我通常发现从你正在做的事情走另一条路更容易。也就是说,使用 XJC 生成 JAXB 对象,然后使用 orm.xml 文件执行到数据库的 JPA 映射。您可以使用标准 XJC 插件和 JAXB 配置文件定制生成的 Java 对象。

这种方法的优点是只维护一组 Java 类(可能带有 JAXB 模型的一些补充子类),并且它还倾向于促进更稳定的 XML 契约。

出于某种原因,人们倾向于看不起使用单独的XML文件进行ORM。不过,有些情况下是有道理的,我相信这是其中一种情况。

看看推土机。假设您有一个 JPA 实体类和一个 JAXB 类。推土机是一个框架,用于在两个这样的豆子之间进行映射。但是,您需要指定应将哪个属性映射到何处。

最新更新