7

I've read Spring Data JPARepository: How to conditionally fetch children entites. But I want to use convenient JPA annotations rather than manual join all children.

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). I do not want to auto fetch credentialList nor actionList . But when I access them, I expect them to be an empty List rather than LazyInitializationException.

Can I use the fields even when I did not specifically JOIN FETCH them in @Query. Just leave it to be an empty list.

If not, Is there anyway to achieve same needs?

Community
  • 1
  • 1
Qiaosen Huang
  • 1,093
  • 1
  • 10
  • 25
  • 3
    What's the point of this? If they are not representing an entity relation, why are they even defined within the entity? – Arnold Galovics Mar 07 '17 at 19:23
  • As galovics says it is a little cumbersome to do it this way. If you assume something is empty then you should not process it and thats it. If you want it to be dynamically loaded then lazy loading is the way to go. Also as SCI points out you can build an entity where the collections are skipped and I assume BaseModel is that entity in your code. The question here is why would you write the relations if you are not going to use them? – Nord Mar 13 '17 at 21:59

2 Answers2

3

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.

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.

SCI
  • 546
  • 3
  • 6
0

I think you are trying to do JOIN but not FETCH, may be just using child objects' attributes in where condition. I wonder something like this will work in JPQL.

@Query("Select u from UserModel u INNER JOIN u.credentialList c
 INNER JOIN u.actionList a")
smile
  • 498
  • 7
  • 18