2

One of my DAO methods contains the following method:

@Override
public boolean isAvailable(String code) {
    Criteria criteria = getSession().createCriteria(MyEntity.class);
    cr.add(Restrictions.eq("code", code).ignoreCase());
    cr.setProjection(Projections.rowCount());
    Long rowCount = (Long) cr.uniqueResult();
    return (rowCount > 0) ? true : false;
}

On the last line the following exception is thrown:

org.hibernate.exception.DataException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2452)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2192)
at org.hibernate.loader.Loader.list(Loader.java:2187)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1706)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at org.hibernate.impl.CriteriaImpl.uniqueResult(CriteriaImpl.java:369)

The code is primary key in this table. Hibernate is generating its select command in console. When I am checking this select command in SQL console in my database it returns correct values. So what am I doing wrong?

GingerHead
  • 8,130
  • 15
  • 59
  • 93
woyaru
  • 5,544
  • 13
  • 54
  • 92

2 Answers2

1

Look at this other question. The method uniqueResult returns at least a Number, then try this:

long rowCount = ((Number)cr.uniqueResult()).longValue();
return (rowCount > 0) ? true : false;
Community
  • 1
  • 1
Esteve
  • 1,789
  • 18
  • 23
  • I have checked out also with this: `Object rowCount = cr.uniqueResult();` and the problem was still the same. Number extends Object, so it should work, by exception is the same. – woyaru Oct 25 '12 at 16:12
  • Then maybe you have an error in the type mapping of your entity. It's also possible that only some values (rows) returned from your query are not matching with your mapped types. – Esteve Nov 20 '12 at 15:33
0

Solution to my problem was very tricky. The parameter code in my method in question above was the key to solution. At the beginning I have column corresponding to this parameter in Hibernate entity class, defined as a varchar with 5 signs length. In the meantime I had to change its length to only 2 signs. But I was invoking the method still with 5 signs String length. And this is why my error has occurred. I have changed again length of the varchar to the 5 signs and everything is alright in this moment.

woyaru
  • 5,544
  • 13
  • 54
  • 92