org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

It seems like your query returns more than one result check the database. In documentation of query.uniqueResult() you can read: Throws: org.hibernate.NonUniqueResultException – if there is more than one matching result If you want to avoid this error and still use unique result request, you can use this kind of workaround query.setMaxResults(1).uniqueResult();

Hibernate Criteria vs HQL: which is faster? [closed]

I’m the guy who wrote the Hibernate 3 query translator back in 2004, so I know something about how it works. Criteria, in theory should have less overhead than an HQL query (except for named queries, which I’ll get to). This is because Criteria doesn’t need to parse anything. HQL queries are parsed with an … Read more

Hibernate criteria: Joining table without a mapped association

This is indeed possible with criteria: DetachedCriteria ownerCriteria = DetachedCriteria.forClass(Owner.class); ownerCriteria.setProjection(Property.forName(“id”)); ownerCriteria.add(Restrictions.eq(“ownername”, “bob”)); Criteria criteria = getSession().createCriteria(Pet.class); criteria.add(Property.forName(“ownerId”).in(ownerCriteria)); Update: This actually performs a sub-query instead of a join but it allows you to use Criteria on two entities that do not have a hibernate relationship defined.

org.hibernate.QueryException: illegal attempt to dereference collection

billProductSet is a Collection. As such, it does not have an attribute named product. Product is an attribute of the elements of this Collection. You can fix the issue by joining the collection instead of dereferencing it: SELECT count(*) FROM BillDetails bd JOIN bd.billProductSet bps WHERE bd.client.id = 1 AND bps.product.id = 1002

Proper way of writing a HQL in ( … ) query

I am unsure how to do this with positional parameter, but if you can use named parameters instead of positional, then named parameter can be placed inside brackets and setParameterList method from Query interface can be used to bind the list of values to this parameter. … Query query = session.createQuery(“FROM Cat c WHERE c.id … Read more

IN-clause in HQL or Java Persistence Query Language

Are you using Hibernate’s Query object, or JPA? For JPA, it should work fine: String jpql = “from A where name in (:names)”; Query q = em.createQuery(jpql); q.setParameter(“names”, l); For Hibernate’s, you’ll need to use the setParameterList: String hql = “from A where name in (:names)”; Query q = s.createQuery(hql); q.setParameterList(“names”, l);

How do you create a Distinct query in HQL

Here’s a snippet of hql that we use. (Names have been changed to protect identities) String queryString = “select distinct f from Foo f inner join foo.bars as b” + ” where f.creationDate >= ? and f.creationDate < ? and b.bar = ?”; return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar});