Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I believe property access vs. field access is subtly different with regards to lazy initialisation.</p> <p>Consider the following mappings for 2 basic beans:</p> <pre class="lang-xml prettyprint-override"><code>&lt;hibernate-mapping package="org.nkl.model" default-access="field"&gt; &lt;class name="FieldBean" table="FIELD_BEAN"&gt; &lt;id name="id"&gt; &lt;generator class="sequence" /&gt; &lt;/id&gt; &lt;property name="message" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; &lt;hibernate-mapping package="org.nkl.model" default-access="property"&gt; &lt;class name="PropBean" table="PROP_BEAN"&gt; &lt;id name="id"&gt; &lt;generator class="sequence" /&gt; &lt;/id&gt; &lt;property name="message" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>And the following unit tests:</p> <pre><code>@Test public void testFieldBean() { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); FieldBean fb = new FieldBean("field"); Long id = (Long) session.save(fb); tx.commit(); session.close(); session = sessionFactory.openSession(); tx = session.beginTransaction(); fb = (FieldBean) session.load(FieldBean.class, id); System.out.println(fb.getId()); tx.commit(); session.close(); } @Test public void testPropBean() { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); PropBean pb = new PropBean("prop"); Long id = (Long) session.save(pb); tx.commit(); session.close(); session = sessionFactory.openSession(); tx = session.beginTransaction(); pb = (PropBean) session.load(PropBean.class, id); System.out.println(pb.getId()); tx.commit(); session.close(); } </code></pre> <p>You will see the subtle difference in the selects required:</p> <pre class="lang-none prettyprint-override"><code>Hibernate: call next value for hibernate_sequence Hibernate: insert into FIELD_BEAN (message, id) values (?, ?) Hibernate: select fieldbean0_.id as id1_0_, fieldbean0_.message as message1_0_ from FIELD_BEAN fieldbean0_ where fieldbean0_.id=? 0 Hibernate: call next value for hibernate_sequence Hibernate: insert into PROP_BEAN (message, id) values (?, ?) 1 </code></pre> <p>That is, calling <code>fb.getId()</code> requires a select, whereas <code>pb.getId()</code> does not.</p>
 

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