如何使用Hibernate使用@XmlElement访问子元素

问题描述 投票:0回答:1

我有一张桌子:

table:
    id
    name
    phone-area
    phone-number

这个XML

<person>
    ...

    <phone>
        <area>111</area>
        <number>123-4567</number>
    </phone>

</person>

而这段代码:

@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
@Table(name = "person", schema = "test")
public class UserLinkedIn {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;
    // ...

    @XmlElement(name = "area")
    @XmlElementWrapper(name="phone")
    @Column(name = "phone-area")
    double area; 

    @XmlElement(name = "number")
    @XmlElementWrapper(name="phone")
    @Column(name = "phone-number")
    double number;
}

但是当我运行它时,我收到此错误:

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
@XmlElementWrapper is only allowed on a collection property but "com.myproject.user.person" is not a collection property.
    this problem is related to the following location:
        at @javax.xml.bind.annotation.XmlElementWrapper(namespace=##default, name=phone, required=false, nillable=false)

我认为“包装器”注释将处理包装元素以获取子值。我错过了什么吗?

**我无法更改架构和xml文件。

java xml hibernate
1个回答
0
投票

我找到了解决方案

我不得不创建另一个类“手机”并将值映射到每个元素

所以在我的主要班级:

@Transient
@XmlElement(name = "phone")
private Phone phone;

然后在我的新班上

@XmlRootElement(name = "phone")
static class Phone {
    @XmlElement(name = "area")
    @Column(name = "area")
    int area;
    @XmlElement(name = "number")
    @Column(name = "number")
    int number;

    // here area = 111
    // pnumber = 123-4567
}
© www.soinside.com 2019 - 2024. All rights reserved.