我有两张表: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;
}
}
在我的书中,我的字段为author
。如何从一位作者那里获得所有书籍?我该如何解决?
我必须使用HQL
或其他方法吗?我是初学者。
答案 0 :(得分:0)
我不会在这里使用代码来帮助你,但是逻辑...... 您需要做的第一件事是使用注释@OneToMany或@ManyToOne在作者和书籍之间建立关系,具体取决于您的结构。
接下来,使用“作者类对象”来检索“书籍”列表。
答案 1 :(得分:0)
首先需要两个实体之间的映射。
@OneToMany(mappedBy="author")
private Set<Book> books= new HashSet<Book>(0);
@ManyToOne
private Author author;
之后,您可以使用简单的条件查询来检索相关记录。