Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conditional FetchTypes in Hibernate OneToMany Mappings.

 
Alan Clark
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right up front... This is a NON-URGENT question! (I'm just trying to broaden my knowledge past where Cameron has got me )

Having just finished "Hibernate Made Easy" (McKenzie) I've been trying to expound the benefits of ORM to a highly experienced DBA at work.

After explaining the Team-has-Players example (OneToMany annotation), and delving deeper in to the FetchType = LAZY or EAGER, he asked the following rather obvious question ...

"What if sometimes you want to fetch the Team without the Players (LAZY) but other times you want it with all the Players (EAGER)?"

He expanded the Team-has-Players example to a League-has-Teams-have-Players example...
His point was that fetching the League object from the DB might be an acceptable hit on the DB (when accessing all the Team records), but that the hit may be unacceptable if Hibernate automatically drilled-down even further to fetch all the Players for each team.

So the question is, can you control the length of Fetch on a per-query basis, rather than just once (using annotations) in the Class file?

Cheers guys.

Alan
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's an interesting and important question.

The short answer is 'no', out of the box, you can either mark your assocation eagar or lazy. So, your team has players? When the team is loaded, the players are either loaded eagarly, or they are not. It depends on your mapping.

So, what do I do in these situations? Well, I mark the assocation lazy. However, remember that you can prompt a loading of all the associated entities with a simple getter call. So, when you need logic, you write logic!

So, you could have a class with two methods, perhaps one called getTeam(), and another called getTeamAndPlayers().


/* this returns the team in a lazy fashion, as the mapping is lazy */


/*this returns the team with players loaded eagerly, despite team/player association being lazy*/



Hopefully you get the idea. It takes a bit of logic, but of course, that's what we do when we have challenges that don't quite fit the out of the box functionality.

See any downsides here?

-Cameron McKenzie

 
Alan Clark
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cameron,

Got it! Well explained!. Even my expert DBA was mollified at that level of control/flexibility.

I'll be back when another hypothetical (or even real) problem occures to me

Cheers,
Alan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic