简体   繁体   English

在Hibernate中持久化LinkedList

[英]Persisting LinkedList in Hibernate

I am trying to persist a Class with a LinkedList Attribute but can't seem to get it right. 我试图坚持一个具有LinkedList属性的类,但似乎无法正确。 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 mapping: Hibernate映射:

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

It seems I can persist objects of the Class Stuff like this but when I try to recover them the following error occurres : 似乎我可以像这样坚持Class Stuff的对象但是当我尝试恢复它们时会发生以下错误:

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

Generally, Hibernate will provide its own implementations for collections so you should prefer interfaces to specific implementations. 通常,Hibernate将为集合提供自己的实现,因此您应该更喜欢特定实现的接口。 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> . 您必须将字段更改为List<Image>

Hibernate (and JPA in general) persists collections using their interfaces. Hibernate(以及一般的JPA)使用其接口来持久化集合。 The list must be declared as a List , and not as a LinkedList . 该列表必须声明为List ,而不是LinkedList And it won't be loaded with a LinkedList instance, because Hibernate uses its own List implementation to implement dirty-checking, lazy-loading, etc. 并且它不会加载LinkedList实例,因为Hibernate使用自己的List实现来实现脏检查,延迟加载等。

It's a good practice to program on interfaces rather than programming on concrete implementations in general. 对接口进行编程是一种很好的做法,而不是通常对具体实现进行编程。 In JPA entities, it's mandatory. 在JPA实体中,它是强制性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM