Win a copy of Kotlin Cookbook this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Joe Ess
  • salvin francis

Can I have the result of JOIN FETCH if I write findBy?

 
Greenhorn
Posts: 3
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I have an entity PERSON, with a lazy fetched field of EYE_COLOR (that has an ID column and COLOR column).

If I write in a the Repository of PERSON findByName, it returns a PERSON with the ID of its EYE_COLOR, and null in COLOR.
I can fetch a PERSON and his EYE_COLOR if I write @Query("FROM PERSON AS p JOIN FETCH EYE_COLOR AS ec WHERE NAME=:name").

Can I somehow write only findBy, and have an annotation (or have other options) to say I want to eagerly fetch EYE_COLOR without having to write the entire @Query?
 
Saloon Keeper
Posts: 21474
144
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, This is a question about Spring JPA.

Entities in JPA exist in one of 2 primary states: attached and detached. While they are attached, you should be able to retrieve any lazy-fetched item or item property by simply using the "get" methods with no query coding at all.

When you are detached, attempts to fetch lazy items will return a null for simple objects and a special "invalid" collection for x-to-many references.

The easiest way to avoid that problem is to force-fetch the lazy items that interest you before you detach. You can do that by simply doing a "get" on the lazy object or one of its properties. You don't have to use what you fetched, it's the fetching that matters, since it forces the lazy load to actually load.

Alas, once detached, if you need a lazy value, the only way to get it is to re-attach (via a merge()) and then force-fetch. Note that merge returns a different object than what you pass it, even though they both look like the same object. The merge return object is the one with the magic in it.
 
Think of how stupid the average person is. And how half of them are stupider than that. But who reads this tiny ad?
Sauce Labs - World's Largest Continuous Testing Cloud for Websites and Mobile Apps
https://coderanch.com/t/722574/Sauce-Labs-World-Largest-Continuous
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!