[英]hibernate java select queries
我对此并不陌生,今天我尝试使用一种返回选定行结果的方法播放休眠状态...如果被选中,那么它可以将结果返回为int ..这是我的方法
public int validateSub(String slave, String source, String table){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery("from Subscribers where slave = :slave AND source = :source AND tbl = :tbl");
q.setParameter("slave", slave);
q.setParameter("source", source);
q.setParameter("tbl", table);
int result = q.executeUpdate();
return result;
}
通过这种方法,我尝试验证从订户表中获得的3个值,但最后,我尝试进行编译并出现此错误
Exception in thread "Thread-0" org.hibernate.hql.QueryExecutionRequestException: Not supported for select queries [from com.datadistributor.main.Subscribers where slave = :slave AND source = :source AND tbl = :tbl]
在这里您要选择记录,因此无需选择关键字就可以
sessionFactory sesionfatory;
ArrayList list = (ArrayList)sessionfactory.getCurruntSession().find(from table where name LIKE "xyz");
long size = list.get(0);
您可以看一下下面的链接,它们说明executeUpdate的工作方式,一个来自休眠文档,另一个来自JPA的Java文档,它们定义了方法何时抛出异常。
http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#executeUpdate()
https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#executeUpdate()
或者,您可以使用
List list = query.list();
int count = list != null ? list.size() : 0;
return count;
您正在运行选择查询,即使您未在此处使用select关键字,hibernate也会将其添加为生成的SQL的一部分。
您需要做的事来避免例外是说
q.list();
现在,这将返回一个列表( 这里是文档)。 如果您要获取元素的大小,可以说
Query q = session.createQuery("select count(s) from Subscribers s where slave = :slave AND source = :source AND tbl = :tbl");
Long countOfRecords = (Long)q.list().get(0);
您也可以在HQL中执行更新语句,它遵循与SQL类似的结构(对象和属性除外)。
希望这可以帮助。
我今天也碰巧犯了同样的错误。
您的SQL语句不正确。
你可以试试:
DELETE from Subscribers WHERE slave = :slave AND source
尝试这个:
int result = q.list().size();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.