Java 休眠从两个表中选择数据

Java 休眠从两个表中选择数据,java,hibernate,Java,Hibernate,我有两个表格:作者和书籍 作者: @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); pu

我有两个表格:
作者
书籍

作者:

 @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类对象检索图书列表

首先,需要创建两个实体之间的映射

作者类
之后,您可以使用简单的条件查询来检索相关记录

HQL或Criteria API可以帮助youTry
Author-Author=session.find(authorId)
然后
session.createQuery(“从书b中选择b,其中b.Author=:a”).setParameter(“a”,Author).list()
。使用google查找更多如何使用HQL和createQueryPS的示例。这里有很好的教程:
@OneToMany(mappedBy="author")
private Set<Book> books= new HashSet<Book>(0);
@ManyToOne
private Author author;