简体   繁体   中英

save many-to-many relationship in corresponding mapping-table

in my Spring-Boot application i want to save a User-Role many-to-many relationship in a corresponding mapping-table in my database, but hibernate gives me an error message.

My User.java class:

@Entity
@Table(name = "users")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id;
  String firstname;
  String lastname;
  String username;
  String password;

  @ManyToMany(mappedBy = "users")
  private Set<Role> roles;
}

My Role.java class:

@Entity
@Table(name = "roles")
public class Role {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id;
  String name;
  String description;

  @ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(
          name = "role_users", 
          joinColumns = 
              @JoinColumn(name = "users_id", referencedColumnName = "id"), 
          inverseJoinColumns = 
              @JoinColumn(name = "roles_id", referencedColumnName = "id")
  )
  private Set<User> users;
}

My run -method:

@Override
@Transactional
public void run(String... strings) throws Exception {
    //add new Roles
    Role roleA = new Role("Rolle A");
    Role roleB = new Role("Rolle B");
    Role roleC = new Role("Rolle C");

    //add new Users
    User userA = new User("FirstnameA", "LastnameA", "UsernameA", "PasswordA");
    User userB = new User("FirstnameB", "LastnameB", "UsernameB", "PasswordB");

    //add new Lists of Roles
    Set<Role> rolesA = new HashSet<Role>();
    rolesA.add(roleA);
    rolesA.add(roleB);
    Set<Role> rolesB = new HashSet<Role>();
    rolesB.add(roleA);
    rolesB.add(roleC);

    //add a list of roles in one user, two times
    userA.setRoles(rolesA);
    userB.setRoles(rolesB);

    //save both users in db
    userRepository.save(userA); //rolle AB
    userRepository.save(userB); //rolle AC

    //give each role the corresponding user
    Set<User> usersA = new HashSet<User>();
    usersA.add(userA);
    usersA.add(userB);
    roleA.setUsers(usersA);
    roleRepository.save(roleA);
    Set<User> usersB = new HashSet<User>();
    usersB.add(userA);
    roleB.setUsers(usersB);
    roleRepository.save(roleB);
    Set<User> usersC = new HashSet<User>();
    usersC.add(userB);
    roleC.setUsers(usersC);
    roleRepository.save(roleC);

}

Hibernate gives me an error message on that:

Cannot add or update a child row: a foreign key constraint fails ( projekt_gra . role_users , CONSTRAINT fk_roleusers_user FOREIGN KEY ( users_id ) REFERENCES users ( id ) ON DELETE CASCADE ON UPDATE CASCADE)

I have the construction from this site and it works with it, but in my code it doesn't work.

I always pass this problem, by rewriting the 2 @ManyToMany relations to @OneToMany to a new entity which deliveres me the table inbetween.

A good reason is that when I have @ManyToMany relations, I can never really easily get whatever I want, as I get carthetic products. Having this table inbetween as an entity totally removes this problem for me.

So, to wrap up:

  • You already have your User , and your Role class, those are almost OK
  • Create a new Entity: UserRole , with properties: User user and Role role
  • Change the two @ManyToMany in User and Role to @OneToMany's to your new @Entity UserRole
  • Add the relations in UserRole : 2 @ManyToOne relations to User and Role .

You now got the problem gone, and extra: a posibility to query on the relation UserRole.

I solved it! Thanks to a friend, i solved my Problem. If it interests somebody: i tried to save a user in the repository first, then the role. And because the role doesn't exist in the moment i want to save my user, Hibernate gave me that error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM