JPA实体管理器未正确更新具有OneToMany关系的字段

时间:2012-11-12 17:52:45

标签: hibernate jpa merge entity one-to-many

我正在使用Hibernate 4.1.0.Final和hibernate-jpa-2.0-api。我在使用实体管理器更新具有OneToMany关系的实体时遇到问题。这是实体:

@GenericGenerator(name = "uuid-strategy", strategy = "uuid.hex")
@Entity
@Table(name = "cb_organization", uniqueConstraints = {@UniqueConstraint(columnNames={"organization_id"})})
public class Organization implements Serializable
{

    …
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
    @JoinTable(name = "cb_organization_address",
              joinColumns = @JoinColumn(name = "organization_id"),
              inverseJoinColumns = @JoinColumn(name = "address_id"))
    private List<Address> addresses;

当我尝试使用新的一对多列表更新实体(使用实体管理器的合并方法)时,地址不会被保存。我像这样创建列表......

    List<Address> addresses = new ArrayList<Address>();
    addresses.add(address);
    ...
    org.setAddresses(addresses);
    m_orgDao.save(org);

以及相关的DAO代码......

@Autowired
private EntityManager entityManager;

@Override
public Organization save(Organization organization)
{
    if(StringUtils.isEmpty(organization.getId()))
    {
        entityManager.persist(organization);
    }
    else 
    {
        organization = entityManager.merge(organization);
    }

    return organization;
}

返回的组织有一个地址,其中所有字段都为空。对于我的实体经理和实体,我可以做些什么来确保数据保持正确?

1 个答案:

答案 0 :(得分:1)

 @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})  

而不是

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)