在Hibernate中持久化LinkedList [英] Persisting LinkedList in Hibernate
问题描述
我正在尝试使用LinkedList属性持久化一个类,但似乎无法正确。这是我的代码和映射:
I am trying to persist a Class with a LinkedList Attribute but can't seem to get it right. Here is my code and my mapping:
import java.util.LinkedList;
public class Stuff implements java.io.Serializable {
private long id;
private LinkedList<Image> images;
public Stuff() {
}
public Stuff(long Id) {
id = Id;
}
public long getId() {
return id;
}
public void setId(long mealId) {
id = mealId;
}
public LinkedList<Image> getNumberImages(int number) {
assert (number >= 0);
return (LinkedList<Image>) images.subList(0, number) ;
}
public LinkedList<Image> getImages() {
return images;
}
public LinkedList<Image> setImages(LinkedList<Image> images) {
this.images = images;
}
public void addImage(Image image) {
if (!images.contains(image)) {
images.add(image);
}
}
Hibernate映射:
Hibernate mapping:
<hibernate-mapping>
<class name="data.Stuff" table="Stuff">
<id name="id" type="long" access="field">
<column name="ID" />
<generator class="assigned" />
</id>
<list name="images" inverse="false" table="IMAGE" lazy="true" access="field">
<key>
<column name="ID" />
</key>
<list-index></list-index>
<one-to-many class="data.Image" />
</list>
</class>
</hibernate-mapping>
似乎我可以像这样坚持Class Stuff的对象,但是当我尝试恢复它们时错误发生:
It seems I can persist objects of the Class Stuff like this but when I try to recover them the following error occurres :
Hibernate: select stuff0_.ID as ID0_, stuff0_.NAME as NAME0_, meal0_.GROUPING as GROUPING0_ from MEAL meal0_
org.hibernate.PropertyAccessException: could not set a field value by reflection setter of data.Meal.images
推荐答案
通常,Hibernate将为集合提供自己的实现,因此您应该更喜欢接口到特定的实现。它可能试图为图像分配不同类型的列表并失败。您必须将您的字段更改为列表< Image>
。
Generally, Hibernate will provide its own implementations for collections so you should prefer interfaces to specific implementations. It's probably attempting to assign a different kind of list to images and failing. You would have to change your field to List<Image>
.
这篇关于在Hibernate中持久化LinkedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!