Hibernate batch delete not working? - java

I am trying to batch delete data from table . For that am setting parameter list for deletion.
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(4);
Session session1 = sfactory.openSession();
Transaction txn1 = session1.beginTransaction();
Query query = session1.createQuery("delete from QueueData tbl where tbl.iID in =:id");
query.setParameter("id", ids);
int i = query.executeUpdate();
txn1.commit();
I am getting exception while executing statement.
SEVERE: line 1:61: unexpected token: =
Exception in thread "main"
org.hibernate.hql.ast.QuerySyntaxException:
unexpected token: = near line 1, column 61 [delete from
hibernetexamples.QueueData tbl where tbl.iID in =:id]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:31)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:24)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:59)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:258)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:157)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
at hibernetexamples.HibernetExamples.main(HibernetExamples.java:104)

You should be aware of basic sql.
IN condition syntax
Your delete query should look like:
"delete from QueueData tbl where tbl.iID in (:id)"

Related

Hibernate runtime exception SQLGrammarException

Hibernate gives me a run time error to the following query.It's saying that there is a syntax error.
ERROR: Syntax error: Encountered "," at line 1, column 16.
Note that transaction handling handled at the service layer that's why session related lines are not in the code.
String hql = "UPDATE Lecturer L set L.id=:id,L.name=:name,L.department=:department,L.center=:center,L.facultyType=:facultyType,L.rank=:rank,L.level=:level,L.building.id=:buildingId,L.building.building=:building where L.id=:prevId";
Query query = session.createQuery(hql);
query.setParameter("id", lecturerDTO.getId());
query.setParameter("name", lecturerDTO.getName());
query.setParameter("department", lecturerDTO.getDepartment());
query.setParameter("center", lecturerDTO.getCenter());
query.setParameter("facultyType", lecturerDTO.getFacultyType());
query.setParameter("rank", lecturerDTO.getRank());
query.setParameter("level", lecturerDTO.getLevel());
query.setParameter("buildingId", lecturerDTO.getBuildingDTO().getId());
query.setParameter("building", lecturerDTO.getBuildingDTO().getBuilding());
query.setParameter("prevId", prevId);
query.executeUpdate();

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 with Hibernate HQL - unexpected token:

***import org.hibernate.Query;***
String hql = "FROM :className WHERE userCreate like ':userName'";
Query query = session.createQuery(hql);
query.setParameter("className", className);
query.setParameter("userName", userName);
List<Node> result = query.list();
And have an error
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: : near line 1, column 6 [FROM :className WHERE userCreate like ':userName']
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at com.SDC.DAO.DAOFileAndFolderService.findUserCreteFileOrFolder(DAOFileAndFolderService.java:36)
at com.SDC.View.Main.main(Main.java:57)
Exception in thread "main" java.lang.NullPointerException
at com.SDC.View.Main.main(Main.java:58)
You cannot use named parameters for Hibernate queries. You can get around this by manually appending the name of the table into your hql string. Your code would look instead like this:
String hql = "FROM " + className + " WHERE userCreate like ':userName'";
Query query = session.createQuery(hql);
query.setParameter("userName", userName);
List<Node> result = query.list();

JPA + SPRING=DAO. Dynamic Parameter List

I can't resolve error with dynamic parameter list "where in". Another query working
#NamedQuery(name = "News.delete", query = "DELETE n FROM News n WHERE n.newsId in (:ids)")
but
Caused by: java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V
at org.hibernate.hql.antlr.HqlBaseParser.optionalFromTokenFromClause(HqlBaseParser.java:400)
at org.hibernate.hql.antlr.HqlBaseParser.deleteStatement(HqlBaseParser.java:259)
at org.hibernate.hql.antlr.HqlBaseParser.statement(HqlBaseParser.java:148)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:248)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:157)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:402)
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:352)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:132)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:221)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:251)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1390)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1359)
UPD
new error
public void removeNews(List<Integer> listOfIdNewsForDeleting) throws DAOException {
EntityManager entityManager = getJpaTemplate().getEntityManagerFactory().createEntityManager();
Query query = entityManager.createNamedQuery("News.delete");
query.setParameter("ids", listOfIdNewsForDeleting);
int deleted = query.executeUpdate();}
javax.persistence.TransactionRequiredException: Executing an update/delete query
I can't get transaction. So i can't use JpaTemplate pass list of id of news for deleting. Maybe JpaCallback
You are having incompatible versions of hibernate and antlr. Upgrade your antlr.jar
Use DELETE FROM News n WHERE n.newsId in (:ids)
See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#batch-direct for the reference.

Categories