[英]save many-to-many relationship in corresponding mapping-table
在我的Spring-Boot應用程序中,我想在數據庫的對應映射表中保存一個User-Role 多對多關系 ,但是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);
}
休眠給我一個錯誤信息:
不能添加或更新子行,外鍵約束失敗(
projekt_gra
。role_users
,約束fk_roleusers_user
外鍵(users_id
)參考文獻users
(id
)ON DELETE CASCADE ON UPDATE CASCADE)
我有此站點的構造,並且可以使用它,但是在我的代碼中它不起作用。
我總是通過將2個@ManyToMany關系重寫為@OneToMany到一個新的實體來解決這個問題,該實體為我提供了介於兩者之間的表。
一個很好的理由是,當我擁有@ManyToMany關系時,就永遠無法像獲得carthetic產品那樣真正輕松地獲得想要的東西。 將此表作為一個實體完全可以消除此問題。
因此,總結一下:
現在,問題解決了,而且還有:可以查詢UserRole關系。
我解決了! 多虧了一位朋友,我解決了我的問題。 如果有人感興趣:我試圖先在存儲庫中保存用戶,然后再保存角色。 而且由於該角色在我要保存用戶的那一刻不存在,因此Hibernate給了我該錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.