我是 Hibernate 新手,所以我的问题可能有点愚蠢,因为我被困住了,很高兴获得帮助。
我有两个实体:书籍和标签,其结构如下:
@Entity
public class BookEntity{
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String author;
private String publisher;
private int edition;
private int yearOfPublishing;
@Id
@Column(name = "isbn")
private String isbn;
@ElementCollection(fetch = FetchType.EAGER)
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinTable(joinColumns = { @JoinColumn(name = "isbn") },
inverseJoinColumns = { @JoinColumn(name = "tagId") })
private List<Tag> tags;
//getters & setters
<小时/>
@Entity
public class Tag implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int tagId;
private String tagValue;
//getters & setters
插入工作正常,这是 HQL 查询:
insert into PUBLIC.BookEntity
(author, edition, publisher, title, yearOfPublishing, isbn)
values (?, ?, ?, ?, ?, ?)
insert into PUBLIC.Tag
(tagId, tagValue)
values (null, ?)
选择查询看起来也不错:
select
bookentity0_.isbn as isbn35_1_,
bookentity0_.author as author35_1_,
bookentity0_.edition as edition35_1_,
bookentity0_.publisher as publisher35_1_,
bookentity0_.title as title35_1_,
bookentity0_.yearOfPublishing as yearOfPu6_35_1_,
tags1_.isbn as isbn35_3_,
tag2_.tagId as tagId3_,
tag2_.tagId as tagId36_0_,
tag2_.tagValue as tagValue36_0_
from
PUBLIC.BookEntity bookentity0_
left outer join
PUBLIC.BookEntity_Tag tags1_
on bookentity0_.isbn=tags1_.isbn
left outer join
PUBLIC.Tag tag2_
on tags1_.tagId=tag2_.tagId
where
bookentity0_.isbn=?
但是当我从数据库加载 BookEntity 时,我得到了带有空标签列表的正确对象。 从数据库加载对象:
public T read(PK id) {
LOG.debug("Reading by id={}", id.toString());
return (T)getSession().get(type, id);
}
其中 T 是 BookEntity,类型是 Class,PK 是 String。
我做错了什么? 提前致谢。
最佳答案
首先,选择 isbn 作为主键并不是最有灵感的想法。如果用户输入错误并输入了错误的 isbn 怎么办?
其次,在我看来,您正在尝试将书籍与标签之间的多对多关系映射起来。或者也许是一对多?
对于多对多用途:
@ManyToMany
@JoinTable(name = "book_tag",
joinColumns = {@JoinColumn(name = "isbn")},
inverseJoinColumns = {@JoinColumn(name = "tag_id")}
)
一对多使用:
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "isbn", nullable = false)
但是你最好用 book_id 替换 isbn。
关于java - hibernate 一对多。从数据库加载时获取空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8042364/