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.
Related
I have below query o delete records from SYBASE database. I am using Spring NamedParameterJDBCTemplete
String query = "Delete FROM PRODUCTS WHERE ID IN (:ids)"
Have written below function to delete records
void deleteRecords(List<ID> ids){
SqlParameterSource parameters = new MapSqlParameterSource("ids", ids);
try{
namedParameterJDBCTemplate.update(query, parameters)
}
catch(Exception e){
}
}
I keep getting error below
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [Delete from PRODUCTS WHERE ID IN ()]; nested exception is com.sybase.jdbc4.jdbc.SybSQLException: Incorrect syntax near ')'
Still new to hibernate custom queries.
My table is
ID TID R1 Position
1 1 1 2
2 1 1 3
I want a custom query to delete rows with TID 1 and R1 1
My current sql looks like
#Query(value = "delete from Table t where t.TID= :tid and t.R1 = :r1", nativeQuery = true)
void deleteByTIDAndR1(#Param("tid") Integer TID, #Param("r1") Integer r1);
It gives me the following error:
.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
My controller retrieves the right tid and r1 ID's.
Is it even possible to delete multiple rows at once? And where could my error be?
Edit
After I add #Modyfying to the query i get the error
TransactionRequiredException: Executing an update/delete query
And after i add #Transactional in combination with #Modifying i get
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't where t.tid= 1 and t.R1 = 99' at line 1
I think you lack the #Modifying annotation, indicating a query that modify the database:
#Modifying
#Query(value = "delete from Table where TID= :tid and R1 = :r1", nativeQuery = true)
void deleteByTIDAndR1(#Param("tid") Integer TID, #Param("r1") Integer r1);
And yes this method can delete zero, one or more rows.
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"
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.
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());
}