我有三个表-role
,user
和user_role
。应该是ManyToMany
,但是由于我也想为user_role
生成ID,因此我使用了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;
}
然后,这就是我创建它们的实例并将其保存到数据库的方式:
// 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);
无论我如何尝试和搜索,我都很难解决该问题:
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]
请帮助我。谢谢。
答案 0 :(得分:2)
斯特恩有很好的观点。您正在尝试仅保存 user
实体,但是在任何地方都没有任何级联设置。因此,当您调用userRepository.save(user)
时,显然是缺少角色实体。在保存user
之前先保存相关实体,或者更好的方法是,在User类的userRoles
字段上方添加级联。
答案 1 :(得分:0)
正如其他地方所提到的,您需要保持最低要求:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = CascadeType.ALL)
private Set<UserRole> userRoles;
或最低:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade =
CascadeType.PERSIST)
private Set<UserRole> userRoles;
但是,如果您需要通过UserRoles
来获取User
,则需要设置:
// for each UserRole in the list.
userRole.setUser(user);
在保留之前,否则将不会填充列表。