Monday, March 10, 2008

Many to many relationship in JPA

I'm using JPA here and I got two objects A and B, the relationship is many to many and B is the owner.
I want to delete object A but still preserving B, the problem is I got a constraint exception since there's a record in the link table which keep a reference to the record that I intended to delete in A.

The solution is to create a native query to remove the row in the link table, then I can remove A.
Hibernate (as my friend said) doesn't have this limitation, so far I don't find the same solution in JPA.

Regarding HQL, there're times where I must revert back to native query to get things done correctly and I wonder is it me that doesn't really know HQL or is it HQL's limitation? sample case I hope will follow later.


Anonymous said...

What JPA provider do you use? I normally use OpenJPA.

With OpenJPA, if you use foreign keys in your underlying database (and you should), set this option in your persistence.xml:

<property name="openjpa.jdbc.SchemaFactory" value="native(ForeignKeys=true)"/>

OpenJPA will now automatically insert, update and delete records in the various tables in the right order. No constraint exceptions!

Santoso said...

I'm using Hibernate's, the one that come with JBoss.

do you know the similar property for Hibernate?

Anonymous said...


I tried to use the same but the returned collection when accessed gives null value. Can u pls provide the solution for this at the earliest.

Thanks in advance