Hibernate 注释与集合

发布于 2024-10-25 03:06:30 字数 1220 浏览 2 评论 0原文

我正在尝试使用休眠注释来实现我的模型。我有 3 个类:图像、人物和标签。 Tags 是一个由 4 个字段组成的表,id、personId、imageId 和createdDate。 Person 具有名称、id、出生日期等字段。我的图像类定义如下:

@Entity
@Table(name="Image")
public class Image {
    private Integer imageId;
    private  Set<Person> persons = new HashSet<Person>();

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    public Integer getImageId() {
        return imageId;
    }

    public void setImageId(Integer imageId) {
        this.imageId = imageId;
    }

    @ManyToMany
    @JoinTable(name="Tags",
                joinColumns = {@JoinColumn(name="imageId", nullable=false)},
                inverseJoinColumns = {@JoinColumn(name="personId", nullable=false)})
    public Set<Person> getPersons() {
        return persons;
    }

    public void setPersons(Set<Person> persons) {
        this.persons = persons;
    }

如果删除 getPersons() 方法上的注释,我可以使用这些类并添加和删除记录。我想获取带有图像的所有标签,并且我正在尝试使用一组标签。我不断收到以下错误:

org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: com.exmaple.persons, no session or session was closed

有人可以帮助我并让我知道我做错了什么吗?

谢谢

I am trying to implement my model using hibernate annotations. I have 3 classes, image, person, and tags. Tags is a a table consisting of 4 fields, an id, personId, imageId, and a createdDate. Person has the fields name, id, birthdate, etc. My image class is defined as follows:

@Entity
@Table(name="Image")
public class Image {
    private Integer imageId;
    private  Set<Person> persons = new HashSet<Person>();

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    public Integer getImageId() {
        return imageId;
    }

    public void setImageId(Integer imageId) {
        this.imageId = imageId;
    }

    @ManyToMany
    @JoinTable(name="Tags",
                joinColumns = {@JoinColumn(name="imageId", nullable=false)},
                inverseJoinColumns = {@JoinColumn(name="personId", nullable=false)})
    public Set<Person> getPersons() {
        return persons;
    }

    public void setPersons(Set<Person> persons) {
        this.persons = persons;
    }

If I remove the annotations on the getPersons() method I can use the classes and add and remove records. I want to fetch all the tags with the image and I am trying to use a set. I keep getting the following error:

org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: com.exmaple.persons, no session or session was closed

Can someone please help me and let me know what I am doing wrong?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花辞树 2024-11-01 03:06:30

此错误消息(实际上与您的关联映射策略或注释无关)意味着您在 Session 关闭后尝试访问域对象之一上的延迟加载集合。

解决方案是禁用此集合的延迟加载,在 Session 关闭之前显式加载该集合(例如,通过调用 foo.getBars().size()),或者确保 Session 保持打开状态,直到不再需要为止。

如果您不确定延迟加载是什么,这是 Hibernate 手册中的部分

This error message - which actually has nothing to do with your association mapping strategy or annotations - means that you have attempted to access a lazy-loaded collection on one of your domain objects after the Session was closed.

The solution is to either disable lazy-loading for this collection, explicitly load the collection before the Session is closed (for example, by calling foo.getBars().size()), or making sure that the Session stays open until it is no longer needed.

If you are not sure what lazy-loading is, here is the section in the Hibernate manual.

南街女流氓 2024-11-01 03:06:30

感谢马特的回复。我现在很困惑。我检索图像的查询如下所示:

public Image findByImageId(Integer imageId) {
    @SuppressWarnings("unchecked")
    List<Image> images = hibernateTemplate.find(
            "from Image where imageId=?", imageId);
    return (Image)images.get(0);
}

我认为我可以调用单个 hql 查询,如果我的映射正确,它将带回关联的数据。

我正在这个链接中查看这个示例 hibernate映射

2.2.5.3.1.3. Unidirectional with join table
A unidirectional one to many with join table is much preferred. This association is described through an @JoinTable.

@Entity
public class Trainer {
    @OneToMany
    @JoinTable(
            name="TrainedMonkeys",
            joinColumns = @JoinColumn( name="trainer_id"),
            inverseJoinColumns = @JoinColumn( name="monkey_id")
    )
    public Set<Monkey> getTrainedMonkeys() {
    ...
}

@Entity
public class Monkey {
    ... //no bidir
}         Trainer describes a unidirectional relationship with Monkey using the join table TrainedMonkeys, with a foreign key trainer_id to Trainer (joinColumns) and a foreign key monkey_id to Monkey (inversejoinColumns).

Thanks for the response matt. I am confused now. My query to retrieve the image looks like this:

public Image findByImageId(Integer imageId) {
    @SuppressWarnings("unchecked")
    List<Image> images = hibernateTemplate.find(
            "from Image where imageId=?", imageId);
    return (Image)images.get(0);
}

I thought that I can call the single hql query and if my mappings are correct it will bring back the associated data.

I was looking at this example at this link hibernate mappings:

2.2.5.3.1.3. Unidirectional with join table
A unidirectional one to many with join table is much preferred. This association is described through an @JoinTable.

@Entity
public class Trainer {
    @OneToMany
    @JoinTable(
            name="TrainedMonkeys",
            joinColumns = @JoinColumn( name="trainer_id"),
            inverseJoinColumns = @JoinColumn( name="monkey_id")
    )
    public Set<Monkey> getTrainedMonkeys() {
    ...
}

@Entity
public class Monkey {
    ... //no bidir
}         Trainer describes a unidirectional relationship with Monkey using the join table TrainedMonkeys, with a foreign key trainer_id to Trainer (joinColumns) and a foreign key monkey_id to Monkey (inversejoinColumns).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文