【问题标题】:How to access child element using @XmlElement with Hibernate如何使用带有 Hibernate 的 @XmlElement 访问子元素
【发布时间】:2018-11-16 00:59:30
【问题描述】:

我有一张桌子:

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】:

    我找到了解决办法

    我必须创建另一个类“电话”并将值映射到每个元素

    所以在我的主要课程中:

    @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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 2019-04-02
      相关资源
      最近更新 更多