中保存多对多关系我想在我的数据库的相应映射表中保存一个用户角色多对多关系,但是hibernate给出了我一个错误消息。在我的Spring-Boot应用程序的相应映射表
我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);
}
休眠给我一个错误消息:
无法添加或更新子行:外键约束失败(
projekt_gra
。role_users
,约束fk_roleusers_user
外键(users_id
)参考文献users
(id
)ON DELETE CASCADE ON UPDATE CASCADE)
我从this site建设,并与它的工作原理,但在我的代码这是行不通的。
你是指[this](https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)? –
不完全。你有你的用户,和你的角色类。将ManyToMany更改为OneToMany的新实体:UserRole。用2个ManyToOne关系创建用户和角色。你现在已经解决了问题,还有额外的问题:查询关系的可能性。 (我将添加这个到我的答案澄清更多) –
谢谢你的努力。我问公司里的一个朋友,我真的在工作,他帮助了我。我发布了解决方案作为答案。 –