I'm new to hibernate and I'm trying the second level cache.
My entities are Team : OneToMany : Player
The team entity :
@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class Team {
...
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@OneToMany(fetch=FetchType.LAZY, mappedBy="team")
@Cascade(CascadeType.ALL)
private List<Player> players;
...
}
the Player entity :
@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class Player extends Person {
...
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@ManyToOne(fetch=FetchType.LAZY)
@Cascade(CascadeType.SAVE_UPDATE)
private Team team;
....
}
My TeamDao is :
@Repository
public class TeamDao {
@Autowired
private SessionFactory sessionFactory;
...
@Transactional
public Team getTeam(Integer id) {
return (Team) sessionFactory.getCurrentSession().createQuery("from team t inner join fetch t.players p where t.id = :tid")
.setParameter("tid", id)
.setCacheable(true)
.uniqueResult();
}
...
}
When i load a team for example id=1, I find it in the second level cache. But I don't find the players list of the team loaded even if the association is declared cacheable. session.getCache().contains(Team.class, 1); returns true but session.getCache().contains(Player.class, 1) returns false
When I try to get a player of the loaded team,
Player player = playerDao.getPlayer(1);
Hibernate generates a select to get the Player even if The Team loaded contains this player
Player player = team.getPlayer().get(0);
Is there a probleme in my entities annotations ? I don't know why it doesn't work for me.
Thanks for helping
The solution is to configure the query cache, using spring xml configuration :
<prop key="hibernate.cache.use_query_cache">true</prop>
because the HQL request createQuery(query) doesn't add the result to the second cache level, not like hibernate methods such get, load, save, update, ...
The use of setCacheable(true) in the HQL query tells hibernate to put the result in the query cache.
The only remaining little problem is that it is not working for a collection of teams (It works for just one Team).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments