Chetan Pulate
Chetan Pulate

Reputation: 503

Hibernate many to many association delete error

I have two classes: Employee and Award, with a many-to-many relationship.

When trying to delete I get a constraint violation error. I went through all the posts but none were helpful.

This is the code:

@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;

Upvotes: 3

Views: 2047

Answers (2)

Tiago Farias
Tiago Farias

Reputation: 3407

You're mapping it wrong, try it like this:

@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

Always look at the examples in the reference before, it will make your life so much easier. ;)

Upvotes: 1

Avihai Marchiano
Avihai Marchiano

Reputation: 3927

You get it from the database and not from hibernate. When hibernate deletes, it first nullifies the reference. Remove the database constraint. You should also turn on hibernate sql logging or see sql in database profiler to see what hibernate does. You will see there the sql that causes the constraint violation.

Upvotes: 0

Related Questions