多对多关系,使用相同实体

huangapple go评论71阅读模式
英文:

Many-To-Many relationship with same Entity

问题

我有一个名为User的实体,可以是Manager或者ClientManager可以拥有多个Client,而每个Client也可以拥有多个Manager

我尝试按照以下方式映射User实体:

@Id
@GeneratedValue(strategy = AUTO)
private UUID uuid;

@ManyToMany
@JoinTable(name = "managers_clients",
    joinColumns = {
        @JoinColumn(name = "clientUuid", referencedColumnName = "uuid", nullable = false)},
    inverseJoinColumns = {
        @JoinColumn(name = "managerUuid", referencedColumnName = "uuid", nullable = false)})
private List<UserEntity> managers;

@ManyToMany(mappedBy = "managers")
private List<UserEntity> clients;

但不幸的是,我遇到了一个错误:

failed to lazily initialize a collection of role: com.company.domain.common.entities.UserEntity.managers, could not initialize proxy - no Session

有人可以解释为什么会出现这个问题以及如何解决吗?非常感谢!

英文:

I have a User entity which can be a Manager or Client, Manager can have many Clients and Client can have many Managers.

I tried to map the User entity like this:


  @Id
  @GeneratedValue(strategy = AUTO)
  private UUID uuid;

  @ManyToMany
  @JoinTable(name = &quot;managers_clients&quot;,
      joinColumns = {
          @JoinColumn(name = &quot;clientUuid&quot;, referencedColumnName = &quot;uuid&quot;, nullable = false)},
      inverseJoinColumns = {
          @JoinColumn(name = &quot;managerUuid&quot;, referencedColumnName = &quot;uuid&quot;, nullable = false)})
  private List&lt;UserEntity&gt; managers;


  @ManyToMany(mappedBy = &quot;managers&quot;)
  private List&lt;UserEntity&gt; clients;

But unfortunately, I have an error:

> failed to lazily initialize a collection of role: com.company.domain.common.entities.UserEntity.managers, could not initialize proxy - no Session

Can someone explain why this happening and how can I overcome this issue? Many thanks!

答案1

得分: 1

问题在于在获取数据时您没有会话。
我不确定您从何处获取数据,但尝试在此方法中添加 @Transactional。

这将确保JPA使用会话获取数据。

英文:

The problem is that you do not have a session during the fetching of the data.
I'm not sure where you are fetching data, but try to add @Transactional to this method.

This will make sure the JPA uses a session to get the data.

huangapple
  • 本文由 发表于 2020年8月29日 15:46:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63644680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定