簡體   English   中英

休眠從兩個表中選擇數據

[英]hibernate select data from two tables

我有兩個表格: authorsbooks

作者:

 @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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM