【发布时间】:2020-07-13 16:19:20
【问题描述】:
我有以下用户实体。
@Entity
@JsonIgnoreProperties(value = {"createdAt", "updatedAt", "roles", "enabled",
"authorities", "credentialsNonExpired", "accountNonLocked", "accountNonExpired"})
@Data
@Accessors(chain = true)
public class User extends Base implements UserDetails, Serializable {
@Size(min = 4, max = 20)
@NotNull
private String username;
@NotNull
private String password;
@NotNull
@Email
private String email;
@ElementCollection(fetch = FetchType.EAGER)
private List<Role> roles = new ArrayList<>();
private List<Book> bookList = new ArrayList<>();
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles.stream().map(r -> new SimpleGrantedAuthority(r.toString())).collect(Collectors.toList());
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
我希望用户有一个书籍列表,但我在不同的试验中面临不同类型的错误。当我将 @OneToMany 注释放在 bookList 属性上时,出现此错误
failed to lazily initialize a collection of role: com.example.demo.model.User.bookList, could not initialize proxy - no Session
在某些消息来源中,它说要使用 @OneToMany,例如 @OneToMany(mappedBy = "xxx", cascade = CascadeType.ALL, fetch = FetchType.EAGER),在这种情况下,在 Book 实体中,我应该添加用户属性并使用 @ManyToOne 但我不希望 book 实体具有用户属性。我该如何处理?
这是用户服务中的 getBooks 方法。
@Transactional
public GenericResponse findAllBooks(User user) {
Objects.requireNonNull(user);
return genericResponseService.createResponseNoError(user.getBookList());
}
而且我不必在同一个模型中获取类型急切属性,它会抛出
Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException
注意:我不想使用 EAGER 提取类型。
【问题讨论】: