i have the following query in SQL Server 2005:
SELECT distinct(user.id_user), user.name, user.familyname from tbl_users users
inner join tbl_notes notes on users.id_user = notes.id_user
where notes.id_book = 1
I have all the necessary classes mapped and i need to write it using the hibernate API.
So far I have written the following code, but it’s returning null:
hibernateSession = HibernateUtil.getSessionFactory().openSession();
criteria = hibernateSession.createCriteria(TblUsers.class, "users")
.createCriteria("users.id_user", "tblNotes")
.add(Restrictions.eq("tblNotes.idBook", idBook));
criteria.setProjection(Projections.projectionList()
.add(Projections.distinct(Projections.property("users.idUser")))
.add(Projections.property("users.name"))
.add(Projections.property("users.familyName")));
ret = criteria.list();
Or something of this nature. The second “createCriteria” forces a join with the notes table, using your defined relationships. Since it appears that your notes table has a relationship with User (via the user_id column), i’ve assumed you have mapped it so that hibernate can figure out how to get from User to Note. In addition, the resulting Criteria object allows you to set conditions on the note being joined.
Finally, we simply create a ProjectionList to enumerate the projections we want. In this case, we want 1 distinct column along with 2 other columns.
What you’ll get back is a list of Object[].
I have not tested this code, and since you didn’t post your classes, i’m not 100% sure everything is mapped in such a way that you can do a join like this.