I am currently refactoring an application that uses string maipulation to create quite complex HQL queries. However, using Criteria API seems to be preferable cause the code is easier to read/maintain. However, the differences that are described below now produce some unexpected behavior. My question is, how to change the criteria, so that it produces the same list of genres (i.e., filtering the second genre, as done using HQL).
Minimum example that reproduces the problem:
Imagine two tables video and genre that have a many to many relationship with the following entries:
video table (
id, title)
1, video1
genre table(
id, name)
8, Comedy
9, Action
video_genre table (
video.id,
genre.id)
1, 8
1, 9
I now want to query all movies with a certain genre:
Code:
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery("from MovieDAO AS m LEFT JOIN FETCH m.genres AS g WHERE g.id = 8");
List<MovieDAO> list = query.list();
for (MovieDAO movie : list) {
System.out.println(movie.getTitle());
for (GenreDAO genre : movie.getGenres())
System.out.print(genre.getName() +" ");
}
session.close();
The output of this HQL query is:
video1
Comedy
If I use Criteria API to do the same query:
Code:
Session session = HibernateSessionFactory.getSession();
DetachedCriteria criteria = DetachedCriteria.forClass(VideoDAO.class);
criteria.createAlias("genres", "g");
criteria.add(Restrictions.eq("g.id", 8));
List<MetadataDAO> list = criteria.getExecutableCriteria(session).list();
//here comes the same output loop as above
session.close();
the output of the query is:
video1
Comedy Action
As I already said, I cannot explain the different results concerning the list of genres.
Greetings, Christian