如何在Hibernate中使用@XmlElement访问子元素 [英] How to access child element using @XmlElement with Hibernate
本文介绍了如何在Hibernate中使用@XmlElement访问子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张桌子:
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;
}
但是当我运行它时,出现此错误:
But when I run it i get this error:
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)
我认为"wrapper"注释将处理wrapper元素以获取子值.我想念什么吗?
I thought the "wrapper" annotation will take care of the wrapper element to get the child value. Am i missing something?
**我无法更改架构或xml文件.
** I cannot change the schema nor the xml file.
推荐答案
我找到了解决方法
我必须创建另一个类"phone",并将值映射到每个元素
I had to create another class "phone" and map the values to each elements
所以在我的主班上:
@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
}
这篇关于如何在Hibernate中使用@XmlElement访问子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文