Hibernate Native SQL Query retrieving entities and collections

前端 未结 5 1638
谎友^
谎友^ 2020-12-13 06:54

This is my situation, I have two basic POJO\'s which I\'ve given a simple hibernate mapping :

Person
  - PersonId
  - Name
  - Books

Book
  - Code
  - Descr         


        
5条回答
  •  情话喂你
    2020-12-13 07:37

    Expanding on Mathews answer. To force hibernate to only return a list of persons do:

    List peopleWithBooks = session.createSQLQuery(
       "select {p.*}, {b.*} from person p, book b where ").
         .addEntity("p", Person.class)
         .addJoin("b", "p.books")
         .addEntity("p", Person.class)
         .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
         .list();
    

    Associated Book entities will be fetched and initialized without a additional call to the db.

    The duplicate

     .addEntity("p", Person.class)
    

    is necessary because

     .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
    

    operates on the last entity added.

提交回复
热议问题