[英]Spring Data conditionally fetch children
I've read Spring Data JPARepository: How to conditionally fetch children entites . 我读过Spring Data JPARepository:如何有条件地获取孩子们的诱惑 。 But I want to use convenient JPA annotations rather than manual join all children.
但我想使用方便的JPA注释而不是手动加入所有孩子。
Say I have the following Model: 说我有以下型号:
@Entity
public class UserModel extends BaseModel<User> {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<CredentialModel> credentialList = new ArrayList<>();
@ManyToMany
@JoinTable(
name = "users_actions",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "action_id", referencedColumnName = "id")
)
private List<ActionMode> actionList = new ArrayList<>();
}
Fetching credentialList
and actionList
can be a time consuming operation (join fetches, etc). 获取
credentialList
和actionList
可能是一项耗时的操作(连接提取等)。 I do not want to auto fetch credentialList
nor actionList
. 我不想自动获取
credentialList
和actionList
。 But when I access them, I expect them to be an empty List rather than LazyInitializationException
. 但是当我访问它们时,我希望它们是一个空的List而不是
LazyInitializationException
。
Can I use the fields even when I did not specifically JOIN FETCH
them in @Query
. 即使我没有在
@Query
专门JOIN FETCH
,我也可以使用这些字段。 Just leave it to be an empty list. 把它留作一个空列表吧。
If not, Is there anyway to achieve same needs? 如果没有,无论如何都有相同的需求吗?
Returning empty Collections would lead to a problem: You couldn't distinguish between a really empty collection and one, that just isn't lazily loaded. 返回空集合会导致一个问题:你无法区分真正空的集合和一个,只是没有延迟加载。 You could check for the collections before accessing them through
org.hibernate.Hibernate.isInitialized(...)
or PersistenceUnitUtil#isLoaded(...)
in JPA2. 您可以在通过JPA2中的
org.hibernate.Hibernate.isInitialized(...)
或PersistenceUnitUtil#isLoaded(...)
访问它们之前检查集合。
However I would suggest you to use Data-Transfer-Objects at this point. 但是我建议你在这一点上使用数据传输对象。 For the special use-case, where the collections are not needed, just build a similiar copy of your entity without that unnesseccary properties.
对于不需要集合的特殊用例,只需构建一个类似的实体副本,而不需要那些不必要的属性。 Of course your DTO building must be done within an open session.
当然,您的DTO大楼必须在公开会议中完成。
I think you are trying to do JOIN but not FETCH, may be just using child objects' attributes in where condition. 我认为你正在尝试JOIN而不是FETCH,可能只是在where条件中使用子对象的属性。 I wonder something like this will work in JPQL.
我想这样的东西在JPQL中会起作用。
@Query("Select u from UserModel u INNER JOIN u.credentialList c
INNER JOIN u.actionList a")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.