0

I tried to make the question smaller, but I could not make it smaller :(

I have 2 entities and this is how they are related:

Collection (1) ----> (n) Item
Item (0 or 1) -----> (n) Item

i.e. each Item is related to a Collection. Further each Item can have 0 or more children Item. In case there is a child Item, the child Item will have a non-null parent_item_id;

Tables:

Collections

collection_id raw

Items

item_id raw
collection_id raw
parent_item_id raw

Mappings :

class Collections
{
   @Id @Column("collection_id")
   String id;

   @OneToMany(fetch=FetchType.EAGER, cascadeType.ALL, mappedBy="collection")
   List<Items> items;
}

class Items
{
  @Id @Column("item_id")
  String id;

  @ManyToOne(optional=false)
  @JoinColumn(name="collection_id")
  Collections collection;

  @ManyToOne(optional=true)
  @JoinColumn(name="parent_item_id")
  Items parentItem;
}

Suppose I have created an object like this:

//Constructor parameters are the Ids.
Collections collection1 = new Collections("1234");
Items i1 = new Items("111");
Items i2 = new Items("222");
item1.parentItem = item2;
item1.collection = collection1;
item2.collection = collection1;
List<Items> listItems = new ArrayList<Items>(1);
listItems.add(item2);
collection1.items = listItems;

We have a Data Access Layer (DA) which is a wrapper around JPA with Hibernate. Next, I perform two operations:

Collections collection1 = DA.merge(collection1);
Collections collection2 = DA.find(collection1.id);

I would expect collection2.items.size() to return 2. But it returns 1. (PS : there are actually 2 items related to the collection1).

Can it be explained? Is it expected or is it a bug in DA? Does JPA cache the Collection?

Later, if in a different transaction, I try to fetch Collections collectionNew = DA.find("1234").items.size() it returns 2 (expected);

TJ-
  • 14,085
  • 12
  • 59
  • 90

1 Answers1

0

What is the items.size() in collection1 before and after the merge? JPA entities are regular objects, so if the size isn't 2, it wont be after a find unless you refresh the entity back from the database.

Chris
  • 20,138
  • 2
  • 29
  • 43
  • Yes it is 1. Okay, I see. and How do I force it to fetch from database? – TJ- Jan 30 '13 at 17:09
  • Maintain both sides of bidirectional relationships is the better approach, or you can use em.refresh after a comit or flush to get changes. – Chris Jan 30 '13 at 21:43