Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it legal to replace a list by an other one in an Hibernate JPA entity?
    primarykey
    data
    text
    <p>Assume a Hibernate 4.2 JPA 2.0 entity <code>class EntityA</code>, it contains a <code>@ManyToOne</code> field <code>List&lt;EntityB&gt; bs</code>. Up to now I strongly believed that I must not replace <code>bs</code> by an <code>new</code> List, instead I have to use the list methods <code>clear</code>, <code>add</code> and <code>remove</code>.</p> <p>To day I wanted to show a college that it will cause problems when I replace the List with an new one, but nothing strange happed, it worked, the database and the entity was updated correctly. Now I am confused: <strong>Is it with the hibernate 4.x JPA 2 allowed to replace a collection of an persisted entity?</strong></p> <p>The two enities, with a OneToMany relation ship, maintained by the one-site.</p> <pre><code>@Entity public class EntityA { @Id long id; @OneToMany public List&lt;EntityB&gt;bs; } @Entity public class EntityB { @Id long id; hashCode and equals based on id } </code></pre> <p>The test, that did not find a problem</p> <pre><code>@Test @Transactional public testReplaceSet { //given: a persistent entity a that contains a persistent entity b1 EntityA a = this.entityManager.persist(new EntityA()); EntityB b1 = this.entityManager.persist(new EntityB()); a.bs = new ArrayList(); a.bs = b1; this.entityManager.flush(); //when: assining a NEW List with an new persistent Entity b2 EntityB b2 = this.entityManager.persist(new EntityB()); a.bs = new ArrayList(); a.bs = b2; long aId = a.id; this.entityManager.flush(); this.entityManager.clear(); //then: the collection is correct stored EntityA AReloaded = this.entityManager.find(EntityA.class, aId); //here I expected the failure, but there was no! assertEquals(b2, AReloaded.bs.get(0)); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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.
 

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