I have two table with many-to-many relations. I mapped this two entities when I am persisting users doesn\'t insert anything to join table. I am debugging till the persist,
You need to enable cascade
for merge (using PERSIST
) or all operations with ALL
.
@ManyToMany(mappedBy = "usersList", cascade = CascadeType.PERSIST)
private List groupsList;
If I set CascadeType.PERSIST, it insert data to groups table too. I want to add date users table and user_group table (pk_user, pk_group)
The way a mapping/join table works is that user_group
would have a foreign key constraint on user
and group
table. That's why a new row in group
has to be inserted for its primary key to be used to add a new row to user_group
.
This has nothing to do with JPA and the same would apply to you even if you were using plain JDBC instead. This is how Entity-Relationships work in database.
Also I dropped all tables and they were generated by eclipse link automatically. They are same but don't insert any row to 'user_group'.
This behaviour is controlled by the eclipselink.ddl-generation
property specified for your persistence-unit
. When specified as drop-and-create-tables
, EclipseLink recreates the whole database schema (deleting any existing data in the process).
This, however, is enabled just to ease your development. This isn't supposed to be used in production environments where its disabled by not specifying this property or by setting its value as none
.