SQL错误:1452,SQLState:23000使用eclipse链接

时间:2017-04-27 15:27:25

标签: java spring eclipselink

我已经映射了我的实体

@Entity
@Table(name = "user", schema = "swprojekt", catalog = "" , uniqueConstraints = {
        @UniqueConstraint(columnNames = "user_id") })
public class UserEntity {
    private int userId;
    private String firstName;
    private String lastName;
    private String password;
    private String email;
    private String addressHouseNumber;
    private String addressStreet;
    private String addressCity;
    private String addressState;
    private String phoneNumber;
    private int isAdmin;
    private List<DoctorspecializationEntity> specializations = new ArrayList<DoctorspecializationEntity>();

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(
            name="join_doctor_specialization_to_user",
            joinColumns=@JoinColumn(name="user_id", referencedColumnName="user_id"),
            inverseJoinColumns=@JoinColumn(name="doctor_specialization_id", referencedColumnName="doctor_specialization_id"))

    public List<DoctorspecializationEntity> getSpecializations() {
        return specializations;
    }

    public void setSpecializations(List<DoctorspecializationEntity> specializations) {
        this.specializations = specializations;
    }

    @Id
    @Column(name = "user_id", nullable = false)

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

和医生专业化

@Entity
@Table(name = "doctorspecialization", schema = "swprojekt", catalog = "")
public class DoctorspecializationEntity {
    private String name;
    private int doctorSpecializationId;
    private List<UserEntity> users;

    @ManyToMany(mappedBy="specializations")
    public List<UserEntity> getUsers() {
        return this.users;
    }

    public void setUsers(List<UserEntity> users) {
        this.users = users;
    }

    @Id
    @Column(name = "doctor_specialization_id", nullable = false)
    public int getDoctorSpecializationId() {
        return doctorSpecializationId;
    }

    public void setDoctorSpecializationId(int doctorSpecializationId) {
        this.doctorSpecializationId = doctorSpecializationId;
    }

他们有m:n的关系。在数据库中,生成用于保存其主键的附加表。我在使用foregin密钥插入数据时遇到问题。

目前我正在使用

                userDAO.add(u); // Add user to database
                u.getSpecializations().add( docSpec ); // Add specialization to user
                userDAO.update( u ); // Update table in database thus inserting in m:n table foregin key of user and specialization.

添加和更新实现如下

@Transactional
public void add(UserEntity u) {
  em.persist(u);
}

   @Transactional
    public  void update( UserEntity u ){
        em.merge( u );
    }

但是我得到的结果相同,那就是

SQL错误:1452,SQLState:23000,无法添加或更新子行:外键约束失败

更新表时,用户实例的主键已经存在,专业化的主键也存在,那为什么还要抱怨?

有没有一种很好的解决方法?

感谢您的帮助

0 个答案:

没有答案