英文:
Many-To-Many relationship with same Entity
问题
我有一个名为User
的实体,可以是Manager
或者Client
,Manager
可以拥有多个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 = "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;
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论