We have spent two days reading documentation, consulting experts, searching the web, etc. on a Hibernate issue that seems very, very obvious, to no avial. Any help will be appreciated.
We are using Hibernate (3.2.1.ga) with annotations (also 3.2.1.ga). We have two persistent classes, called "Survey" and "Page". Each survey consists of a list of pages, and each page consists of a list of questions (but only the fact that Surveys contain lists of Questions is relevant here). So we write:
Code:
@Entity
public class Page
{
@Id @GeneratedValue
Long id;
private String title;
@OneToMany(cascade = {CascadeType.ALL})
@IndexColumn(name = "position")
private List<Question> questions;
...
}
Code:
@Entity
public class Survey
{
@Id @GeneratedValue
Long id;
private String title;
@OneToMany(cascade = {CascadeType.ALL})
@IndexColumn(name = "position")
private List<Page> pages;
...
}
This seems like a pretty basic example of a uni-directional @OneToMany. Now the trouble is that, as far as we can tell, delete from a persistent List does not work because it generates a uniqueness constraint violation. If we delete the last element of the pages list, everything is ok (a single delete sql statement is issued). But if we delete any other element, then
sometimes we get:
Quote:
Hibernate: select survey0_.id as id4_0_, survey0_.created as created4_0_, survey0_.title as title4_0_ from Survey survey0_ where survey0_.id=?
Hibernate: select pages0_.Survey_id as Survey1_1_, pages0_.pages_id as pages2_1_, pages0_.position as position1_, page1_.id as id1_0_, page1_.title as title1_0_, page1_.introText as introText1_0_ from Survey_Page pages0_ left outer join Page page1_ on pages0_.pages_id=page1_.id where pages0_.Survey_id=?
Hibernate: delete from Survey_Page where Survey_id=? and position=?
Hibernate: update Survey_Page set pages_id=? where Survey_id=? and position=?
with things like
Quote:
[WARN] SQL Error: 0, SQLState: null
[WARN] Batch entry 0 update Survey_Page set pages_id=52 where Survey_id=41 and position=0 was aborted. Call getNextException to see the cause.
[WARN] SQL Error: 0, SQLState: 23505
[WARN] ERROR: duplicate key violates unique constraint "survey_page_pages_id_key"
So what is going on here? Since this is a very basic example in which we let Hibernate use whatever defaults it wants, it seems odd that this should not work. I can provide more info, if you think that will help, but I am afraid we are hitting against something fairly obvious.
By the way, list insertion and addition works. It looks like whether deletion works depends on how the order of deletions relates to the order of insertions. We are removing elements with the List.remove method. We have not defined equal and hashCode for Page. Note that DELETE_ORPHAN is irrelevant (it does not help), as it only causes the deleted Page to be remove from page table, it has nothing to do with the survey_page table, which is where the problem lies.
Thank you,
Andrej