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).

 @Entity
 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 

SELECT 
player.name,..... 
FROM 
Player player
where 
player.team_id = ?

2.
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
FROM
Player player
WHERE
player.id = ?
AND
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.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
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.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}