rbottel
rbottel

Reputation: 131

Constraintviolation on a nonmodified collection/entity

For the past few days I've been banging my head against a very frustrating problem.

We have a large number of hibernate entities which is all generated code. That means that following @OneToMany collections(among other things) are created:

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "tablename")
private java.util.List<classname> fieldname;

In our application we want to be able to copy all this for a second user. We do this by reading all those classes and fields and recreating them later(via their constructors). It seems however that reading this collection causes Hibernate to mark the collection as dirty. This later leads to a strange constraint violation when writing to the database when Hibernate first tries to delete a row and then insert it again.

My problem is this: Why does Hibernate even want to delete and then insert that row? And why does it fail?

My guess is that Hibernate tries to recreating the entire collection because for some reason Hibernate thinks it is modified. However, this is clearly not the case.

Edit: I should point out that using HibernateSession#evict after reading the collection seems to fix the issue. However, this feels very hacky and I prefer a more thoughtout one.

Upvotes: 0

Views: 74

Answers (1)

Ranu Jain
Ranu Jain

Reputation: 577

If Your join table dont have any primary key then hibernate always treat its a new record and try to delete the reference record and insert the new one.

But if your join table has own primary key then it will insert the record if primery key has null, if primery key value is present then it will update other wise it will delete the record which was in table but not in list.

Hibernate required primary key to identfiy the new or old record otherwise it will be always new for Join table case.

Upvotes: 2

Related Questions