简体   繁体   中英

How to properly check if a row exist in database?

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?

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM