开发者

Hibernate Criteria API

开发者 https://www.devze.com 2023-01-30 20:27 出处:网络
I was asked in the interview today about Hibernate eager loading. The question was: If there is an Employee class and an Address Class and relationship:1 employee --> many addresses.

I was asked in the interview today about Hibernate eager loading. The question was: If there is an Employee class and an Address Class and relationship:1 employee --> many addresses. How with a single query one can query Employee class and get all addresses?

I mentioned we can turn on eager loading on Address...but this开发者_如何学JAVA will result in N+1 sqls.

The requirement is to load all employee and adresses using 1 sql. The answer is supposedly something to do with Hibernate Criteria API. When I look on the net, I am not sure how this can be achieved. ANy thoughts would be appreciated.


From the hibernate reference:

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .setFetchMode("mate", FetchMode.EAGER)
    .setFetchMode("kittens", FetchMode.EAGER)
    .list();

This will retrieve a list of cats with name like Fritz% and that have their mate reference already loaded and their kittens collection also already loaded.

Should probably experiment with something like this to check the sql that is generated to see that it is doing an outer join onto the references with the fetch more set to Eager.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号