JPA - OneToMany 斗争

JPA - OneToMany struggle

我有一个实体 Property,它有多个 PropertyAttributes - 作为列表管理,即

@OneToMany(mappedBy = "property", cascade = { CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinFetch(value = JoinFetchType.INNER)
private List<PropertyAttribute> propertyAttribute;

PropertyAttribute 中我也有对 Property 的引用,即

@Id
@JsonIgnore
@JoinColumn(name = "property_id")
@ManyToOne
private Property property; 

当我保存新的 Property 时,例如id=10400 而不是额外的 PropertyAttribute 也使用相同的 ID 保存 - 正如预期的那样。我的 save() 方法如下所示:

public void save(){
   //begin transaction
   getEntityManager.persist(newProperty);
   // end transaction...
   //begin transaction...
   getEntityManager.merge(newPropertyAttriubtes);
   // end transaction
}

但是当我执行第二轮save()时(现在使用id=10401然后我得到奇怪的结果,即:

getEntityManager().find(Property.class,10400)

现在 PropertyAttribute Property - id = 10401,即来自上次保存的记录(=错误内容!)

知道为什么第二次保存失败了吗?可能是数据库问题?还是 EclipseLink?

我终于想出了正确的方法:-/ 以防其他人遇到同样的问题...

public void save(){
   //begin transaction
   getEntityManager.persist(newProperty);
   // end transaction...
   newPropertyAttriubtes.forEach(attr -> {
          //begin transaction...
          getEntityManager.merge(attr);
          // end transaction
          newProperty.attach(attr)
   }
   //begin transaction
   // to have the PropertyAttributes attached in the EntityManager => merge
   getEntityManager.merge(newProperty); 
   // end transaction...
   }
}

感谢 Chris 指出正确的方向,让我在 JPA 管理实体后不更改实体!