[英]hibernate select data from two tables
我有两个表格: authors
和books
作者:
@Entity
@Table (name="authors")
public class Author implements java.io.Serializable {
private Integer id;
private String name;
private String lastName;
/*book list*/
private Set<Book> books= new HashSet<Book>(0);
public Author() {
}
public Author(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public Author(String name, String lastName, Set<Book> books) {
this.name = name;
this.lastName = lastName;
this.books = books;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "AUTHOR_ID", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "AUTHOR_NAME", unique = true, nullable = false, length = 10)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "AUTHOR_LASTNAME", unique = true, nullable = false, length = 10)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "author")
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
}
书:
import javax.persistence.*;
@Entity
@Table(name = "books")
public class Book implements java.io.Serializable {
private Integer id;
private String name;
private Author author;
public Book() {
}
public Book(String name) {
this.name = name;
}
public Book(String name, Author author) {
this.name = name;
this.author = author;
}
@Id
@Column(name = "BOOK_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "BOOK_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "AUTHOR_ID",nullable = false)
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
在我的书的桌子上,我有一个ID为author
字段。 如何从一位作者那里获得所有书籍? 我该如何解决? 我必须使用HQL
或其他方法吗? 我是初学者。
我不会在这里提供代码方面的帮助,但会提供逻辑帮助。.首先,您需要做的是根据结构,使用@OneToMany或@ManyToOne批注在Author和Books之间建立关系。
接下来,使用作者类对象检索“书籍”列表。
首先,您需要两个实体之间的映射。
@OneToMany(mappedBy="author")
private Set<Book> books= new HashSet<Book>(0);
@ManyToOne
private Author author;
之后,您可以使用简单的条件查询来检索相关记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.