我的问题很简单:
user具有addressaddresscitystatecountry组成。

因此,我有这个结构:

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所做的查询?

最佳答案

CascadeType.PERSISTUser.userAddress注释使每个userAddress持久化的User持久化,而CascadeType.PERSISTUserAddress.addressCity注释使每个addressCity持久化的UserAddress持久化。因此,当您保留具有相同城市的用户时,将尝试使用相同的键保留新城市,这会导致违反约束。因此,请删除那些具有ManyToOne注释关系的级联。

您必须检查保存用户是否已经存在userAddress,并检查保存UserAddress内部是否存在关系并采取必要的措施。

关于mysql - 如何保持但避免唯一键异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15845743/

10-12 03:08