Reputation: 405
I'm new to Hibernate so my question can be silly a bit, by i'm stucked and will be glad to get help.
I have two entities: Book and Tag with following structure:
@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
Insertion works fine, here is the HQL queries:
insert into PUBLIC.BookEntity
(author, edition, publisher, title, yearOfPublishing, isbn)
values (?, ?, ?, ?, ?, ?)
insert into PUBLIC.Tag
(tagId, tagValue)
values (null, ?)
Selection queries looks fine also:
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=?
But when i'm loading BookEntity from database i'm getting correct object with empty list of Tags. The loading object from database :
public T read(PK id) {
LOG.debug("Reading by id={}", id.toString());
return (T)getSession().get(type, id);
}
where T is BookEntity, type is Class and PK is String.
What am i doing wrong? Thanks in advance.
Upvotes: 0
Views: 6513
Reputation: 15250
First of all choosing isbn as a primary key is not the most inspired idea. What if the user makes a typo and enters a wrong isbn?
Secondly, it seems to me that you are trying to map a many to many relation from books to tags. Or maybe a one to many?
For many to many use:
@ManyToMany
@JoinTable(name = "book_tag",
joinColumns = {@JoinColumn(name = "isbn")},
inverseJoinColumns = {@JoinColumn(name = "tag_id")}
)
For one to many use:
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "isbn", nullable = false)
But you better replace isbn with a book_id.
Upvotes: 1