Spring Data conditionally pick up children

I read Spring JPARepository Data: how to conditionally invoke child users . But I want to use convenient JPA annotations, rather than manually connecting all the children.

Let's 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<>(); } 

Retrieving credentialList and actionList can take a lot of time (combine selections, etc.). I do not want to automatically extract credentialList and actionList . But when I call them, I expect them to be an empty list, not a LazyInitializationException .

Can I use fields even if I don’t specifically JOIN FETCH them in @Query . Just leave it blank.

If not, is it all the same to achieve the same needs?

+6
source share
2 answers

Returning empty collections will lead to a problem: you cannot distinguish between a truly empty collection and one that is simply not lazily loading. You can check collections before accessing them through org.hibernate.Hibernate.isInitialized(...) or PersistenceUnitUtil#isLoaded(...) in JPA2.

However, I would suggest you use Data-Transfer-Objects at this point. For a special use case where collections are not needed, simply create a similar copy of your object without these insensitive properties. Of course, your DTO building should be done as part of an open session.

+3
source

I think you are trying to make a JOIN but not FETCH, maybe just use the attributes of the child objects in the condition where this condition is. Interestingly, something like this will work in JPQL.

 @Query("Select u from UserModel u INNER JOIN u.credentialList c INNER JOIN u.actionList a") 
0
source

Source: https://habr.com/ru/post/1015493/


All Articles