Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You only have access to the Hibernate Session in the DAO layer. If your associations don't have a <code>FetchType</code> configured, or if they have <code>FetchType.LAZY</code>, then you have two choices, both inside the DAO:</p> <ol> <li>Use <code>Hibernate.initialize</code></li> <li>Get some aspect of the association which forces Hibernate to initialize it</li> </ol> <p>Example 1: <code>Hibernate.initialize(myEntity.getMyAssociation());</code></p> <p>Example 2:</p> <pre><code>if(myEntity.getMyAssociation() != null) { myEntity.getMyAssociation().size(); // forces the association to be loaded } </code></pre> <p>I generally use example 2, because then I can also take advantage of <code>BatchSize</code> for Hibernate to optimize lazy fetches.</p> <p>-----------EDIT 1-----------</p> <p>Example for this case using HibernateTemplate and a callback:</p> <pre><code> public Restaurant load(final Long id) { // need to drop down to Hibernate because of lazy loading, and make sure all properties are loaded HibernateCallback&lt;Restaurant&gt; callBack = new HibernateCallback&lt;Restaurant&gt;() { public User doInHibernate(Session session) throws HibernateException { Query query = session.createQuery("from Restaurant r where r.id=:id").setInt("id", id); Restaurant restaurant = (Restaurant)query.uniqueResult(); Hibernate.initialize(restaurant.getOwner()); Hibernate.initialize(restaurant.getTags()); return restaurant; } }; return getHibernateTemplate().execute(callBack); </code></pre> <p>}</p> <p>-----------EDIT 2----------- And here's how to do it directly in Hibernate:</p> <pre><code>@Repository public class RestaurantDAOImpl implements RestaurantDAO { private SessionFactory factory; @Autowired public RestaurantDAOImpl(SessionFactory factory) { this.factory = factory; } public Restaurant load(Long id) { Query query = session.createQuery("from Restaurant r where r.id=:id").setInt("id", id); Restaurant restaurant = (Restaurant)query.uniqueResult(); Hibernate.initialize(restaurant.getOwner()); Hibernate.initialize(restaurant.getTags()); /* --OR -- if(restaurant.getTags() != null) { restaurant.getTags().size(); } */ return restaurant; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload