实体之间的春季相互关系

时间:2020-04-01 19:35:36

标签: java spring

我有以下用户实体。

@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;
}
}

我希望用户拥有一本书的清单,但在不同的试验中我面临着不同类型的错误。当我在bookList属性上放置@OneToMany注释时,出现此错误

failed to lazily initialize a collection of role: com.example.demo.model.User.bookList, could not initialize proxy - no Session

在某些来源中,它说使用@OneToMany像@OneToMany(mappedBy =“ xxx”, 级联= CascadeType.ALL,提取= FetchType.EAGER),在这种情况下,在Book实体中,我应该添加用户属性并使用@ManyToOne,但我不希望Book实体具有用户属性。我该如何处理?

这是用户服务中的getBooks方法。

@Transactional
public GenericResponse findAllBooks(User user) {
    Objects.requireNonNull(user);
    return genericResponseService.createResponseNoError(user.getBookList());
}

而且我不必在同一模型中获取fetchtype eager属性,它会抛出

Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException

注意:我不想使用EAGER提取类型。

1 个答案:

答案 0 :(得分:1)

据我所知,您想将User映射为Book作为OneToMany。但是仅在一个方向上,从“用户”到“书籍”,而不是相反。 为此,您可以使用单向OneToMany映射。

public class User extends Base implements UserDetails, Serializable {
    ...

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="book_id")
    private List<Book> bookList = new ArrayList<>();

    ....
}

注意:为此,您需要 JPA2.X JPA1.0 不支持。 您了解有关如何使用@JoinColumn here

的更多信息