JPA: problem with many to many relations

L

loris_p

Hi! I'm writing a desktop application using JPA. I have two entities
(User and Movement) with a many to many relation.
This is the part of Movment.java:

@ManyToMany
@JoinTable(
name="USERS_MOVEMENTS",
joinColumns=
@JoinColumn(name="MOVEMENT_ID",
referencedColumnName="ID"),
inverseJoinColumns=
@JoinColumn(name="USER_ID", referencedColumnName="ID")
)
private List<User> users;

and User.java:

@ManyToMany(mappedBy="users")
private List<Movement> movements;

Obviously I have also getters and setters.
users_movements join table has 2 fields: user_id and movment_id.
All seems to work fine, i.e. if I have a record user_id=1 and
movement_id=1 and I assign the movement 1 to user 2 JPA creates a
delete query for 1,1 record and an insert for user_id=2 and
movement_id=1. The problem is when I have a movement associated with 2
users, i.e. movement 1 with user 1 and 2 and I want to delete one of
the two relations: JPA creates a delete query for the relation to
remove, and an insert query for the relation that should remain. The
result is an exception caused by the insert of a duplicate key.
Did I define the relation in the wrong way or did I miss something?
Thanks in advance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top