Jul*_*lez 5 java hibernate jpa spring-data-jpa
我有三个表 - role、user和user_role。这应该是ManyToMany,但因为我也想为 生成 id user_role,所以我使用了OneToMany和ManyToOne。
以下是我的实体,仅包含相关字段:
@Entity
public class Role {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "role")
private Set<UserRole> userRoles;
}
@Entity
public class User {
@Id
private String id;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private Set<UserRole> userRoles;
}
@Entity
public class UserRole {
@Id
private String id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "role_id")
private Role role;
}
Run Code Online (Sandbox Code Playgroud)
然后,这就是我创建它们的实例并将其保存到数据库的方法:
// Retrieve from DB by ID
Role role = ...;
// ID String is generated from UUID
User user = new User();
user.id("abc");
// ID String is generated from UUID
UserRole userRole = new UserRole();
userRole.setId("xyz");
Set<UserRole> userRoles = Set.of(userRole);
role.setUserRoles(userRoles);
user.setUserRoles(userRoles);
userRole.setUser(user);
userRole.setRole(role);
userRepository.save(user);
Run Code Online (Sandbox Code Playgroud)
无论我如何尝试和谷歌搜索,我发现都很难解决这个问题:
2020-09-27 23:41:58.917 WARN 21948 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.example.entity.UserRole with id xyz; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.example.entity.UserRole with id xyz]
Run Code Online (Sandbox Code Playgroud)
请帮我。谢谢。
正如其他地方提到的,您至少需要:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = CascadeType.ALL)
private Set<UserRole> userRoles;
Run Code Online (Sandbox Code Playgroud)
或最小值:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade =
CascadeType.PERSIST)
private Set<UserRole> userRoles;
Run Code Online (Sandbox Code Playgroud)
但如果您需要获取,UserRoles则User需要设置:
// for each UserRole in the list.
userRole.setUser(user);
Run Code Online (Sandbox Code Playgroud)
在坚持之前,否则列表将不会被填充。
小智 3
斯特恩说得有道理。您试图仅 user保存实体,但您没有在任何地方设置任何级联。所以当你调用userRepository.save(user)它时显然缺少角色实体。要么在保存之前保存依赖实体user,或者更好的是,userRoles在用户类等中添加上面的级联字段。
| 归档时间: |
|
| 查看次数: |
5726 次 |
| 最近记录: |