Hibernate 学习记录 4

来源:互联网 发布:node js 教程 编辑:程序博客网 时间:2024/05/20 00:48

这篇,我们将处理一对多的关系。


public class Book extends BaseEntity {    private String name;    public Book() {    }    public Book(String name, Person person) {        this.name = name;        this.person = person;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @ManyToOne    @JoinColumn(name = "personId")    private Person person;    public Person getPerson() {        return person;    }    public void setPerson(Person person) {        this.person = person;    }}

public class Person extends BaseEntity {    private String name;    public Person() {    }    public Person(String name) {        this.name = name;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @OneToMany(mappedBy = "person", fetch = FetchType.EAGER)    private List<Book> bookList;    public List<Book> getBookList() {        return bookList;    }    public void setBookList(List<Book> bookList) {        this.bookList = bookList;    }}

这里同样用到了 mappedBy,

记得之前的提醒吗,

这意味 setBookList 方法不会有实质性的作用。


FetchType 指的是是否用懒加载,

即调用 getBookList 方法 时才进一步查询,这样就分散了查询的压力。

但这里会报错,因为再查询时 session 已经关闭,所以先用 EAGER 吧。


public class Main {    public static void main(final String[] args) throws Exception {        Person li = getLi();        System.out.print(li.getBookList().size());        HibernateUtil.close();    }    private static Person getLi() {        return PersonDao.getPersonById("85d78641-924c-48d3-bfdd-203fa7f7bc9d");    }}


0 0
原创粉丝点击