在我的 Spring-Boot 应用程序中,我想将用户角色多对多关系保存在数据库中相应的映射表中,但 hibernate 给了我一条错误消息。
我的User.java类:
@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;
}
我的Role.java类:
@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;
}
我的运行方法:
@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 给了我一条错误消息:
Cannot add or update a child row: a foreign key constraint fails (
projekt_gra
.role_users
, CONSTRAINTfk_roleusers_user
FOREIGN KEY (users_id
) REFERENCESusers
(id
) ON DELETE CASCADE ON UPDATE CASCADE)
我有 this site 的构造它可以使用它,但在我的代码中它不起作用。
最佳答案
我总是通过将 2 个 @ManyToMany 关系重写为 @OneToMany 到一个新实体来解决这个问题,该实体为我提供了中间的表。
一个很好的理由是,当我有@ManyToMany关系时,我永远无法真正轻松地得到我想要的任何东西,因为我得到了carthetic产品。将此表作为一个实体置于其间完全消除了我的这个问题。
所以,总结一下:
- 您已经拥有了 User 和 Role 类,这些几乎就可以了
- 创建一个新实体:UserRole,其属性为:User user 和 Role role
- 将User和Role中的两个@ManyToMany更改为@OneToMany到您的新@Entity UserRole
- 在UserRole中添加关系:2个@ManyToOne关系到User和Role。
现在问题已经解决了,而且还可以:查询关系 UserRole 的可能性。
关于java - 将多对多关系保存在相应的映射表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42417025/