Hi,
We are testing some JPA code and are having problems with the cascading behaviour of our test code.
Firstly, we have a main Person bean with the following attributes and is the owning side of the two relationships:
Code:
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "firstname")
private String firstname;
@Column(name = "lastname")
private String lastname;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = OccupationJpaImpl.class)
@JoinColumn(name = "occupation_id")
private Occupation occupation;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = BeverageJpaImpl.class)
@JoinTable(name = "person_beverage", joinColumns = { @JoinColumn(name = "person_id") }, inverseJoinColumns = { @JoinColumn(name = "beverage_id") })
private Set<Beverage> beverages;
Each of the non-owning sides are set up as follows:
Beverage:
Code:
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "description")
private String description;
@Column(name = "alcoholic")
private Boolean alcoholic;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "beverages", targetEntity = PersonJpaImpl.class)
private Set<Person> people;
Occupation:
Code:
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "description")
private String description;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "occupation", targetEntity = PersonJpaImpl.class)
private Set<Person> people;
We have a few tests of which one works and the rest fail:
1 - If we remove a Beverage from a collection of beverages belonging to a Person and merge the Person then the underlying join table has the appropriate mapping record removed which we want.
2 - If we remove a Person from a collection of people belonging to a Beverage and merge the Beverage then the underlying join table does not have the appropriate mapping record removed.
3 - If we delete an Occupation then the associated people, and any of their associated records, are not deleted but rather an attempt is made to insert a null into the occupation_id column of the underlying person table. This does not happen if there is no many-to-many relationship on Person to Beverage, then the people are deleted.
4 - If we try an delete a beverage rather than unmapping the beverage to the people and deleting it, it tries to update the underlying person record with a null occupation.
Any explanation as to why 2, 3 and 4 do not work as expected would be greatly appreciated.
Regards,
Chris.