Recently, in a newsms project, you need to use Many-to-many Association mappings, and here are two entity classes that are used in a project: The user class user and role class roles, which are many-to-many relationships.
//user table @Entity @Table (name= "Rong_user") public class user{//omit other content private set<role> roles = new Lin Kedhashset<role> (); Role Collection @ManyToMany (cascade = {cascadetype.persist, cascadetype.merge}) @JoinTable (name = "Rong_user_role", Jo
Incolumns = {@JoinColumn (name = "user_id")}, Inversejoincolumns = {@JoinColumn (name = "role_id")}) @OrderBy ("id")
Public set<role> GetRoles () {return roles;
public void Setroles (set<role> roles) {this.roles = roles; }//Role table @Entity @Table (name= "Rong_role") public class role{//omit other content private set<user> User = new Li Nkedhashset<user> ();
User Collection @ManyToMany (cascade = {cascadetype.persist, cascadetype.merge}, Mappedby = "roles", Fetch = Fetchtype.lazy)
Public set<user> GetUser () {return User;
public void SetUser (set<user> user) {this.user = user; }
}
The three tables in the two build databases, respectively, are Rong_user, rong_role, and an intermediate table Rong_user_role.
Hibernate and JPA Control Association relations, can only be one side, cannot the two sides control, in the above procedure, I by set mappedby= "roles" in the role class to control the relations by the user,
The problem then arises: when I delete role roles, if no user has the role, it can be deleted successfully, and if a user has the role, it cannot be deleted and the following exception is thrown:
12:53:33,125 WARN jdbcexceptionreporter:100-sql error:1451, sqlstate:23000
12:53:33,125 ERROR jdbcexceptionreporter:101-cannot Delete or update a parent ROW:A FOREIGN KEY constraint fails (' News Ms/rong_user_role ', CONSTRAINT ' Fkf1698421a337a5fa ' FOREIGN KEY (' role_id ') REFERENCES ' rong_role ' (' ID ')
12:53:33,171 ERROR abstractflushingeventlistener:324-could not synchronize database
Org.hibernate.exception.ConstraintViolationException:Could not execute JDBC batch update