如何坚持但避免唯一键异常?

时间:2013-04-06 00:40:34

标签: mysql jpa jpa-2.0

我的问题很简单:
useraddressaddresscitystatecountry组成。

所以我有这个结构:

public class User {
  ..
  //bi-directional many-to-one association to UserAddress
  @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
  @JoinColumn(name="id_user_address")
  private UserAddress userAddress;
  ..
}

请注意,CascadeType 拥有CascadeType.ALL,因为如果用户被删除,则不会影响已创建的cities, states and countries

public class UserAddress {
  ..
    //bi-directional many-to-one association to AddressCity
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.})
    @JoinColumn(name="id_city")
    private AddressCity addressCity;

    //bi-directional many-to-one association to AddressCountry
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name="id_country")
    private AddressCountry addressCountry;

    //bi-directional many-to-one association to AddressState
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name="id_state")
    private AddressState addressState;
  ..
}

我的问题是,如果我尝试注册具有相同city的用户,例如它给了我一个例外:

  

严重:由以下原因引起:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:键'city_UNIQUE'的重复条目'Campinas'

我如何避免这种constraint,保留CASCADE
有谁知道如何在我的JSF项目中显示JPA的查询?

1 个答案:

答案 0 :(得分:1)

CascadeType.PERSIST的{​​{1}}注释会导致User.userAddress每个userAddress持久User CascadeType.PERSIST注释UserAddress.addressCity addressCity UserAddress要坚持每个{{1}}持久化。因此,当您持有具有相同城市的用户时,尝试使用导致约束违规的相同密钥来持久保存新城市。因此,删除那些ManyToOne注释关系的级联。

您必须检查保存用户是否已存在userAddress,并检查保存UserAddress是否已存在其中的关系并采取必要的操作。