一尘不染

在Hibernate中保持LinkedList

hibernate

我正在尝试使用LinkedList属性持久化一个类,但似乎无法正确处理。这是我的代码和映射:

 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>
    <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的对象,但是当我尝试恢复它们时,发生以下错误:

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

阅读 219

收藏
2020-06-20

共1个答案

一尘不染

通常,Hibernate将为集合提供其自己的实现,因此您应首选接口而非特定的实现。它可能正在尝试为图像分配其他类型的列表,但失败了。您必须将字段更改为List<Image>

2020-06-20