JPA many-to-many persist to join table

前端 未结 2 1832
遥遥无期
遥遥无期 2020-12-18 04:52

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,

2条回答
  •  北海茫月
    2020-12-18 05:26

    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.

    
    

提交回复
热议问题