简体   繁体   中英

hibernate java select queries

i am new to this and today i tried to play hibernate with a method that returns the result of selected row...if is selected then it can return the result in int.. here is my method

 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;

}

from this method i tried to validate the 3 values that i get from the Subscribers table but at the end i tried to compile having this error

     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]

here you want to select record so it is posible without select key word

sessionFactory sesionfatory;
ArrayList list = (ArrayList)sessionfactory.getCurruntSession().find(from table where name LIKE "xyz");

long size = list.get(0);

You can have a look at the below links that how executeUpdate works, one is from the hibernate docs and other the java docs for JPA which defines when the exception is thrown by the method

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()

Alternatively you can use

 List list = query.list();    
 int count = list != null ? list.size() : 0;
 return count; 

you are running a select query, Eventhough you are not using the select keyword here hibernate will add that as part of the generated SQL.

what you need to do to avoid the exception is the say

q.list();

now, this will return a List ( here is the documentation). if you are trying to get the size of the elements you can say

    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);

you can execute update statements as well in HQL, it follows a similar structure as SQL (except with object and properties).

Hope this helps.

I also happened to make the same mistake today.
Your SQL statement is not correct.

You can try:

DELETE from Subscribers WHERE slave = :slave AND source

尝试这个:

int result = q.list().size();

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