I have three entities, say A, B and C. A contains multiple instances of B and C. B and C have String fields as their primary key which are meant to be populated at runtime. The codes are as follows:
Class A:
@Entity
public class A
{
private int id;
private B[] bSet = null;
private C[] cSet = null;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId()
{return id;}
@OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
@OrderColumn(name = "bIndex")
public B[] getBset()
{return bSet;}
@OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
@OrderColumn(name = "cIndex")
public C[] getCset()
{return cSet;}
}
Class B:
@Entity
public class B
{
private String bId;
private A a;
@Id
public String getBId()
{return bId;}
@ManyToOne(cascade = CascadeType.ALL)
public A getA(A a)
{return a;}
}
Class C:
@Entity
public class C
{
private String cId;
private A a;
@Id
public String getCId()
{return cId;}
@ManyToOne(cascade = CascadeType.ALL)
public A getA(A a)
{return a;}
}
If I try to persist a B entity in my application, Hibernate does not go for an insert, as I saw after enabling Hibernate logging. It is trying for an update, and throwing this exception.
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
This problem hasn't been answered satisfactorily anywhere. I tried here, here and here. As they say, Hibernate expects a primary id of null while saving, and if it's anything else, it goes for updating the row, and throws this exception. But I need to insert rows with these Strings as primary keys. So what can I do for that? Please help me with this.
ADDITIONAL INFO
I think I'm fighting a losing battle here. It seems that this is a bug in Hibernate itself, and until Hibernate devs solve it, we can't do this. Just look here.