Over a million developers have joined DZone.

Hibernate : Write An Specific Query For Better Performance

Sometimes it is not good idea to initialise a collection in Hibernate - just to do collection.contains(member).  Here's my solution.
Sometimes it is not good idea to initialise a collection in Hibernate - just to do collection.contains(member).

Suppose  we have Team class which has players .Team is having one-to-many relationship with Players(of course fetch type is set to lazy).

 public class Team {
 @OneToMany(FetchType = lazy)
 List players;

Now if I want to know that a given player is part of Team .I can do directly players.contains(player) but it has a bit of disadvantage 
1.As soon as you do players.contains(player) ,Hibernate   would make a sql query (if you are using mysql database) something like 

Player player
player.team_id = ?

hibernate would create all player objects in Team   and put all those objects(Players) and in memory(session) ,and might also create snapshot .If there are two many players in Team it would consume lot of memory .

A better approach would be to write a specific HQL query in DAO,like (You can write queries in separate file -as xml file)

SELECT player
Player player
player.id = ?
player.team_id = ?

This query would just create a only one Player object in memory if Team has a given player otherwise it would create null Player object.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}