Hibernate JPA中一对多关系中获取数据的问题

Hibernate JPA中一对多关系中获取数据的问题,hibernate,jpa,one-to-many,dao,many-to-one,Hibernate,Jpa,One To Many,Dao,Many To One,我试图把问题缩小,但我无法缩小:( 我有两个实体,这就是它们之间的关系: Collection (1) ----> (n) Item Item (0 or 1) -----> (n) Item i、 e.每个项目与集合相关。此外,每个项目可以有0个或多个子项目。如果有子项目,子项目将具有非空的父项目id 表格: class Collections { @Id @Column("collection_id") String id; @OneToMany(fetch

我试图把问题缩小,但我无法缩小:(

我有两个实体,这就是它们之间的关系:

Collection (1) ----> (n) Item
Item (0 or 1) -----> (n) Item
i、 e.每个
项目
集合
相关。此外,每个
项目
可以有0个或多个子
项目
。如果有子
项目
,子
项目
将具有非空的
父项目id

表格:

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;
}
收藏

collection_id raw
项目

映射:

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;
}
我希望
collection2.items.size()
返回2。但它返回1。(注:实际上有2个项目与collection1相关)

可以解释吗?这是预期的还是DA中的一个bug?JPA是否缓存集合


稍后,如果在另一个事务中,我尝试获取
collectionNew=DA.find(“1234”).items.size()
它返回2(预期);

items.size()是什么在合并前后的collection1中?JPA实体是常规对象,因此如果大小不是2,则不会在查找之后,除非您从数据库中刷新实体。

是的,它是1。好的,我明白了。我如何强制它从数据库中提取?维护双向关系的两侧是更好的方法,或者您可以使用em。在comit或flush之后刷新以获取更改。
//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;
Collections collection1 = DA.merge(collection1);
Collections collection2 = DA.find(collection1.id);