JPA多次合并所有者触发连接表上的删除

时间:2013-02-15 14:40:50

标签: java hibernate jpa orm many-to-many

我在Customer和BusinessUnit之间有很多关系:

public class Customer extends AbstractEntity {

    @JoinTable(name = "CUS_BUS_UNITS", 
            joinColumns = {
                @JoinColumn(name = "CUS_ID", referencedColumnName = "CUS_ID")},
            inverseJoinColumns = {
                @JoinColumn(name = "BUS_ID", referencedColumnName = "BUS_ID")})
    @ManyToMany
    private Collection<BusinessUnit> businessUnits;
}

public class BusinessUnit extends AbstractEntity {

    @ManyToMany(mappedBy = "businessUnits")
    private Collection<Customer> customers;

}

当我调用entityManager.merge(customer)时;在客户(已经在DB中,没有改变)我在日志中看到这两个sql命令:

  

Hibernate:更新CUSTOMERS设置CUS_DESCR =?,CUS_NAME =?,CUS_ENABLED =?   哪里有CUS_ID =?休眠:从CUS_BUS_UNITS中删除CUS_ID =?

为什么hibernate试图从连接表中删除记录? 我只需要在连接表中更新客户记录和可能的记录 - 取决于我是否在客户上添加或删除了业务单位。不应更新,删除或插入业务单位。

修改 我的equals / hashCode是(在AbstractEntity中定义):

public int hashCode() {
    if (getId() != null) {
        return getId().hashCode();
    }
    return super.hashCode();
}
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    AbstractEntity other = (AbstractEntity) obj;
    if (getId() == null || other.getId() == null) {
        return false;
    }
    if (!getId().equals(other.getId())) {
        return false;
    }
    return true;
}

编辑2 转换器的形式:

@FacesConverter("businessUnitConverter")
public class BusinessUnitConverter implements Converter {

    /**
     * {@inheritDoc}
     */
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        return ((BusinessUnit) object).getId().toString();
    }


    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        BusinessUnit businessUnit = new BusinessUnit();
        businessUnit.setId(Long.parseLong(value));
        return businessUnit;
    }

}

1 个答案:

答案 0 :(得分:3)

我找到了答案:http://assarconsulting.blogspot.fr/2009/08/why-hibernate-does-delete-all-then-re.html

由于使用了Collection,这种行为是正确的(请参阅链接文章)。我使用Set而不是集合,它工作正常。