Performance Zone is brought to you in partnership with:
DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ratn has posted 5 posts at DZone. View Full User Profile

Hibernate : Write An Specific Query For Better Performance

06.07.2010
| 4312 views |
  • submit to reddit
        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<Player> 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.