JPA - OneToMany斗争

时间:2017-08-17 15:51:04

标签: java jpa eclipselink

我有一个实体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,即上次保存的记录(=内容错误!)

任何想法为什么它失败了第二次保存?可能是DB问题?还是EclipseLink?

1 个答案:

答案 0 :(得分:0)

我终于弄清楚如何正确地做到这一点: - /以防其他人挣扎同样......

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管理之后不改变实体!

相关问题