我是Hibernate的新手,所以我的问题可能有些愚蠢,因为我被困住了,很乐意得到帮助。
我有两个实体:Book和Tag,结构如下:
@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。
我做错了什么? 提前谢谢。
答案 0 :(得分:1)
首先选择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。