简体   繁体   中英

Prevent lazy loading in JPA/Hibernate with FetchType.LAZY (especially when using @Transactional)?

I searched around but I only get people asking the opposite of my question. So let's say we have:

@Entity
class Book {
  ...
  @ManyToOne(fetch = FetchType.LAZY)
  private Author author;
}

Is there a (preferably global) property/way in JPA/Hibernate to prevent from ever lazily loading the author (or any entity)?

Don't get me wrong, I don't want to use EAGER fetch. I want to prevent juniors from ever accidentally calling book.getAuthor().getName() and making another DB call. A lot of people are looking to fix their LazyInitializationException, but I basically want to force such an exception to be thrown even if there is an active session (which when using @Transactional is quite an easy mistake to make). However I also still want Author to be fetched if you properly use "JOIN FETCH Author" in your JPQL query.

My particular use case is with Spring and GraphQL. @Transactional quite easily hides when a session is open and avoids the LazyInitializationException. And with GraphQL you can specify which fields to get so I don't want unnecessarily joins when such fields aren't requested (here we use a Field Resolver with a DataLoader).

Would a sufficient workaround be to instead use a projection ( https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections ) of the Book entity without the reference to the author? And by working with different projections guarantee that related entities are not unintentionally loaded?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM