1

A while back on IRC I was told to create copied subLists when merging an entity's relationships in my EJB update method. My question is: is this really necessary?

Here's my code ...

(in CtCaseEJB)

  public CtCase update( CtCase pCase )
  {
    CtCase aCtCase = em.merge( pCase );
    ...
    List<CtCaseTest> aCaseTestList = pCase.getCaseTests();               
    List<CtCaseTest> aNewCaseTestList = new ArrayList<CtCaseTest>();
    for( CtCaseTest aCaseTest : aCaseTestList )
    {
        aCaseTest = em.merge( aCaseTest );
        aNewCaseTestList.add( aCaseTest );
    }
    aCtCase.setCaseTests( aNewCaseTestList );
    ...
    return aCtCase;
 }

The relationship is defined as:

(in CtCase)

private List<CtCaseTest> mCaseTests = new ArrayList<CtCaseTest>();

@OneToMany( mappedBy = "ctCase", cascade = { CascadeType.PERSIST, CascadeType.REFRESH } )
@OrderBy( "rank" )
public List<CtCaseTest> getCaseTests()
{
    return mCaseTests;
}

public void setCaseTests( List<CtCaseTest> pCaseTests )
{
    mCaseTests = pCaseTests;
}

This is how I'm currently doing it, though I'm getting some very occassional wonky behavior (doubled lists are getting created somehow).

My question is: why can't I add CascadeType.MERGE and simply do this in CtCaseEJB ...

  public CtCase update( CtCase pCase )
  {
    return em.merge( pCase );
  }

Why the need for manually merging relationships in JPA/EJB?

teefal
  • 31
  • 4

1 Answers1

1

There is no need to manually merge. Do add CascadeType.MERGE. It is important that your equals() and hashcode() is implemented properly for this to work. My best guess to why you are seeing "wonky" behaviour, doubling of the list/etc, is that there is something wrong with the equals() and/or hashcode().

A side point: I would make a copy of the provided list in setTestCase(), to avoid future problems.

esej
  • 3,059
  • 1
  • 18
  • 22
  • Thanks. Are you saying as general principle to always use copy constructors in setList() methods in JPA? Or is this instance specific. – teefal Apr 29 '12 at 13:28
  • Is it sufficient for equals() and hashcode() to use the entities unique ID (if it exists), with possibly not unique value munging (if not yet)? – teefal Apr 29 '12 at 13:43
  • I prefer it that way, but it is a much discussed and to large extent unresolved problem-area. And people smarter than me would prefer other solutions. `equals` and `hashcode` in ORM frameworks in general and in JPA specifically is complicated. An internet search with relevant terms should provide some text material. – esej Apr 29 '12 at 13:48
  • such as: http://stackoverflow.com/questions/5031614/the-jpa-hashcode-equals-dilemma – teefal Apr 29 '12 at 13:59