Trouble when using clase WHERE ... IN (list) - java

I'm having trouble when trying to retrieve from database using Hibernate. What I'm trying to do is to retrieve questions from the database (using Hibernate with HSQLDB) where the Tag tag is contained in the question list. Here is the error:
06-Jan-2017 19:43:26.021 WARN [http-apr-8080-exec-4] org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions SQL Error: -5585, SQLState: 42585 06-Jan-2017 19:43:26.021 ERROR [http-apr-8080-exec-4] org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions malformed numeric constant: .
Here the query:
Query query = session.createQuery("FROM Question q WHERE (:someTag) in (q.tagList) ORDER BY (q.creationDate) DESC").setParameter("someTag", tag).setMaxResults(amount);
And here the complete method:
public static List<Question> list(Tag tag, int amount){
Session session = HibernateUtil.getSession();
Query query = session.createQuery("FROM Question q WHERE (:someTag) in (q.tagList) ORDER BY (q.creationDate) DESC").setParameter("someTag", tag).setMaxResults(amount);
return query.list();
}

You need to use elements clause if you are trying to check whether a list contains an element, in this case, the query would look like this:
"FROM Question q WHERE :someTag in elements(q.tagList) ORDER BY (q.creationDate) DESC"

Related

Unexpected token error at table alias using hibernate

I am using Spring hibernate.
My code is as below:
String hql = "select a.candidate_id_fk, count(*) from Answers a , Question b where a.question_id_fk = b.id"+""
+"and a.answer=b.correct_answer group by a.candidate_id_fk";
Session session = sessionFactory.getCurrentSession();
List list = session.createQuery(hql).list();
Error:
org.hibernate.hql.internal.ast.ErrorCounter reportError
unexpected token: a

how to fetch last column of the selected table using hibernate?

i am trying to fetch the id of last column in descending order.
the query which returns last column is
select id from(select id from challan
order by id desc) where ROWNUM=1;
now i am trying to do same thing using hibernate.
public long getIdOnChallanTable() {
session = sessionFactory.openSession();
trans = session.beginTransaction();
Query<Object[]> query = session.createNativeQuery("select id
from(select id from challan order by id desc) where ROWNUM=1;");
Long value = 0L;
List<Object[]> list = query.getResultList();
for ( Object lst : list){
Object[] objects =(Object[]) lst;
value=(Long)(objects[0]);
}
return value;
}
and the error is:
2017-07-26 12:37:36 [http-nio-7080-exec-1] WARN :: SQL Error: 911, SQLState: 22019
2017-07-26 12:37:36 [http-nio-7080-exec-1] ERROR:: ORA-00911: invalid character
update error javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
You don't need the semicolon at the end of the query and please use proper whitespacing. In the FROM clause, you don't have the whitespace between the subquery and the FROM keyword.
Note: don't forget to commit/rollback the transaction at the end and handle the exceptions as well. I hope this was just a sketch to show us the problem and not a code from a real world application.

ERROR: org.hibernate.hql.internal.ast.ErrorCounter - line 1:45: unexpected token : DESC on fetching the last record from the table

I am trying to fetch the last record from the database using the below hibernate query
//fetch the last data from a field in a table
Session session = _sessionFactory.getCurrentSession();
Query query = session.createQuery("select t.currentfile from file t DESC");
query.setMaxResults(1);
List<Object[]> rows = query.list();
for (Object[] row: rows) {
System.out.println(" ------------------- ");
System.out.println("current file: " + row[0]);
}
with the above hql I am getting this error:
ERROR: org.hibernate.hql.internal.ast.ErrorCounter - line 1:45: unexpected token
: DESC
what could be wrong?
Descending ('DESC' or 'desc') and Ascending ('ASC' or 'asc') can only be used with an order by clause.
So your code would have to look something like:
Query query = session.createQuery("select t.currentfile from file t
ORDER BY t.time_created DESC");
(time_created is only an example field as you have not added what fields you have in your table or what you are ordering by in descending order)
Your query is wrong. You have to put an ORDER BY yourSortAttribute before the DESC.

How does a native sql query bind fields to an entity instead of map

I tried to run native sql query with resulttransformer (AliasToBeanResultTransformer), it gives error like below.
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.ozpas.ozentegre.entity.EntDevirlog cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
By the way, my native sql query does not include all fields in the entity ( EntDevirlog ), there are only some fields in that entity. shall the query include all fields in the entity ?
as i understood, hibernate transforms result into a map object instead EntDevirlog entity. It uses PropertyAccessMapImpl. how can i solve this problem to get the result as a list ( arraylist ) ? thanks.
Session session = HibernateUtilMikro.getSessionFactory().openSession();
List<EntDevirlog> results = new ArrayList<EntDevirlog>();
Transaction tx = null;
String sql = "mynativequery";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("tarih", tarih);
query.setParameter("srmkodu", srmkodu);
query.setParameter("s1", EnumPanoislemtipleri.islem1.getValue());
query.setParameter("s2", EnumPanoislemtipleri.islem2.getValue());
query.setResultTransformer(new AliasToBeanResultTransformer(EntDevirlog.class));
results = query.list();
tx.commit();
Just use the quotes for the aliases
"select firstName as \"firstName\",
lastName as \"lastName\" from Employee"
Read for a more deeply explanation here:
mapping Hibernate query results to custom class?

hql error in select clause

When I am using HQL select clause following error is occuring .student is mysql table.
Error:
Hibernate: select studentcla0_.vStudentName as col_0_0_ from student studentcla0_
java.lang.String
Below is Code:
public static void querySubject(Session session)
{
String sql_query="select stud.strStudentName from StudentClass as stud";
Query query1=session.createQuery(sql_query);
for(Iterator it=query1.iterate();it.hasNext();)
{
Object[] row = (Object[]) it.next();
System.out.println("Subject Name:"+row[0]);
}
return;
}
is it hql or sql. If sql try:
session.createSQLQuery(...)
Just to confirm - you have a table in your database called "student" and it has a column called "vStudentName" which is a string type of some sort? The mapping is complete, and has resulted in a translation to this SQL:
select studentcla0_.vStudentName as col_0_0_
from student studentcla0_
Does this run against your database directly, or does it error there as well?
When you select a single value (be it property or entity), Hibernate will return that value directly; it will not be wrapped in an Object array. See details here. So your code should be:
for(Iterator it=query1.iterate(); it.hasNext(); ) {
System.out.println("Subject Name:"+ it.next());
}

Categories