Hibernate多对多关联删除错误

时间:2012-07-26 19:27:36

标签: hibernate many-to-many constraints

我有两个班级:EmployeeAward,有多对多的关系。

尝试删除时出现约束违规错误。我查看了所有帖子,但没有一个是有帮助的。

这是代码:

@Entity
@Table(name="TB_AWARD")
public class Award implements Serializable{


    @Id @GeneratedValue
    @Column(name="AWARD_ID")
    private long awardId;

    @ManyToMany(mappedBy="awards")
    @NotFound(action=NotFoundAction.IGNORE)
    private Collection<Employee> employee = new ArrayList<Employee>();

    @Column(name="AWARD_TYPE")
    private String awardType;

    @Column(name="AWARD_DATE")
    private Date awardDate;

    @Column(name="AWARD_DETAILS")
    @Lob
    private String awardDetails;

    @Column(name="REMARK")
    private String remark;

@Entity
@Table(name="TB_EMPLOYEE")
public class Employee implements Serializable {

    @Id @GeneratedValue
    @Column(name="EMPLOYEE_ID")
    private long employeeID;

        @ManyToMany(cascade= CascadeType.ALL)
    private Collection<Award> awards;

2 个答案:

答案 0 :(得分:1)

你把它映射错了,试试这样:

@Entity
@Table(name="TB_AWARD")
public class Award implements Serializable{


    @Id @GeneratedValue
    @Column(name="AWARD_ID")
    private long awardId;

    @ManyToMany(targetEntity=Employee.class, cascade = CascadeType.ALL)
    @JoinTable(name = "AWARD_EMPLOYEE", joinColumns = { @JoinColumn(name ="AWARD_ID")},
    inverseJoinColumns = { @JoinColumn(name = "EMPLOYEE_ID") })
    @NotFound(action=NotFoundAction.IGNORE)
    private Collection<Employee> employees = new ArrayList<Employee>();

    @Column(name="AWARD_TYPE")
    private String awardType;

    @Column(name="AWARD_DATE")
    private Date awardDate;

    @Column(name="AWARD_DETAILS")
    @Lob
    private String awardDetails;

    @Column(name="REMARK")
    private String remark;

@Entity
@Table(name="TB_EMPLOYEE")
public class Employee implements Serializable {

    @Id @GeneratedValue
    @Column(name="EMPLOYEE_ID")
    private long employeeID;

    @ManyToMany(
    cascade = CascadeType.ALL,
    mappedBy = "employees",
    targetEntity = Award.class
    )
    private Collection<Award> awards; //create the getter for this guy

以前一直关注examples in the reference,它会让你的生活变得更加轻松。 ;)

答案 1 :(得分:0)

你从数据库而不是从休眠中获取它。当hibernate删除时,它首先使引用无效。删除数据库约束。 您还应该打开hibernate sql logging或者在数据库探查器中查看sql以查看hibernate的功能。你会看到导致约束违规的sql。