0
我有以下类映射为一对多:读者和书籍,当一个读者可以容纳一个以上的书:休眠选择一对多帮助
书:
@Entity
@Table(name = "book")
public class Book implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String author;
private String title;
public Book(){}
public Book(String author,String title){
this.author = author;
this.title = title;
}
@Id
@GeneratedValue
@Column(name = "BOOK_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "author")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Column(name="title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
//equals and hashcode ommited.
}
读者
@Entity
@Table(name = "reader")
public class Reader implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String firstName;
private String lastName;
Set<Book> set = new HashSet<Book>();
@Transient
public void loanBook(Book book){
set.add(book);
}
@Id
@GeneratedValue
@Column(name = "READER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name="lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@OneToMany(cascade=CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name="READER_ID")
public Set<Book> getSet() {
return set;
}
public void setSet(Set<Book> set) {
this.set = set;
}
public Reader(){}
public Reader(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
现在我想用一些书籍ID取读卡器类,例如:
Reader reader = service.getReaderbyBook(Long.valueOf(10));
我的功能看起来像:
@Override
public Reader getReaderbyBook(Long id) {
Session session = null;
Reader reader = null;
session =sessionFactory.openSession();
org.hibernate.Transaction tr = session.getTransaction();
tr.begin();
String hqlSelect = "Select .... where book.id:=id";
Query query = session.createQuery(hqlSelect);
query.setLong("id", id);
reader = (Reader) query.uniqueResult();
tr.commit();
session.flush();
session.close();
return reader;
}
}
如何我的HQL选择应该是这样,如果我只是想获取一些书相关的单一阅读器?
它的一对多 - 如何创建额外的表帮助? – Nilesh 2011-03-23 08:26:34
@Nilesh:让我们假设你有一张表,主键为reader_id的读者,然后你有主表book_id的表书...现在添加另一个名为Issued_books_by_readers,并为读者添加reader_id和book_id。请记住,一旦图书被退回,请将其保存在历史记录表中,并删除表格中的记录。这是我认为你可以在数据库级别 – Amanpreet 2011-04-14 12:06:02
中处理1到多个这就是多对多! – Nilesh 2011-04-14 13:10:25