2017-08-17 102 views
0

我有哪几种PropertyAttributes实体Property - 管理的名单,即JPA - 一对多奋斗

@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) 

现已PropertyAttributeProperty - id = 10401从上次保存的记录,即(=错误的内容!)

失败的原因有任何想法第二保存?也许这是一个DB-问题?还是EclipseLink的?

+1

这没有意义。如果外键“property_id”是ID,那么OneToMany中如何使用这种关系? OneToMany意味着有很多propertyAttribute具有相同的ID值,这使得它不是唯一的。 ID应该是不可变的:如果使用的字段是需要更改的字段,则不应将其用作ID。还要确保您不仅仅是改变了您已经传递给JPA进行管理的值。 – Chris

+0

thx的提示,即最后一句 - 这导致正确的轨道:-)保存我的一天。 – LeO

回答

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... 
    } 
} 

THX克里斯点我到正确的方向JPA后不改变实体管理它!