***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();
Related
i am tried to get user by criteria, but getting error like below
Error:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: '{test%,testuser6,%ana%}' near line 1, column 108 [
SELECT jpauser FROM com.abc.domain.jpa.JpaUser jpauser WHERE jpauser.username like ANY('{test%,testuser6,%ana%}'::text[]) limit 100]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
Code:
public List<JpaUser> getUserByCriteria(String criteria)
{
Query query = getEntityManager()
.createQuery("SELECT jpauser FROM JpaUser jpauser WHERE " + criteria);
List<JpaUser> result = query.getResultList();
return result;
}
I just copied and executed the query in PostgreSQL terminal, its works fine, but through hibernate query its failed
Here is the query i have executed in PostgreSQL
SELECT * FROM users jpauser WHERE jpauser.username like ANY('{test%,testuser6,%ana%}'::text[]) limit 100
Construct the criteria like below
String value = criteria.get("username");
builder.append(TABLE_ALIAS).append("username").append(" like ")
.append(ANY).append("('{").append(value).append("}'::text[])")
Can any one help on this, how to execute hibernate query with like and multiple input ?
Use createNativeQuery for native query
Query query = getEntityManager()
.createNativeQuery("SELECT jpauser FROM JpaUser jpauser WHERE " + criteria);
In a native query, You need to use native SQL statment:
Query query = getEntityManager()
.createNativeQuery("SELECT * FROM users jpauser WHERE " + criteria)
I am trying to create new object from the result set of HQL query but it is throwing NullPointerException at session.createQuery()
Could someone please show me any flaw in the query that I created?
The idea is to return the type/area/reason along with their count and then create new CasesOverview object with these values.
StringBuilder hql = new StringBuilder("SELECT NEW CasesOverviewDTO(:filterColumnString, Math.toIntExact(count(c.id)), :filter) ");
hql.append("FROM Case AS c ");
hql.append("where c.site.id = :siteId and c.status ");
if(isOpen) {
hql.append("!= :close and createdDate > :startDate and createdDate < :endDate ");
} else {
hql.append("= :close and closedDate > :startDate and closedDate < :endDate ");
}
hql.append("group by :filterColumn");
Query query = exeQuery(hql.toString());
switch(filter) {
case TYPE:
query.setParameter("filterColumnString", "c.area.toString()");
query.setParameter("filterColumn", "c.area");
break;
case CASE_TYPE:
query.setParameter("filterColumnString", "c.type.toString()");
query.setParameter("filterColumn", "c.type");
break;
case RESOLUTION:
query.setParameter("filterColumnString", "c.reason.toString()");
query.setParameter("filterColumn", "c.reason");
break;
}
query.setParameter("filter", filter);
query.setParameter("siteId", siteId);
query.setParameter("close", "CLOSED");
query.setParameter("startDate", startDate);
query.setParameter("endDate", endDate);
In the createQuery method, error is thrown:
Caused by: java.lang.NullPointerException
at org.hibernate.hql.internal.ast.tree.ConstructorNode.formatMissingContructorExceptionMessage(ConstructorNode.java:201)
at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:193)
at org.hibernate.hql.internal.ast.tree.ConstructorNode.prepare(ConstructorNode.java:158)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processConstructor(HqlSqlWalker.java:1095)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2328)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2194)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1476)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:573)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
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.essensys.bluefin.dao.hibernate.HibernateGenericDao.exeQuery(HibernateGenericDao.java:411)
From the stack trace it looks like there's no constructor that would satisfy your CasesOverviewDTO(:filterColumnString, Math.toIntExact(count(c.id)), or if there is, it's not in the same package as the class the hql query is being created in, and therefore needs to be fully qualified (add the package name like new com.some.package.CasesOverviewDTO(args)). Can you please also post your CasesOverviewDTO ?
I am trying to get the User object which has, besides username and password, a boolean variable that states if it has been deleted or not. The boolean var is called delete. In my database all the user entities are false.
I tried the ClassicalSyntax but it gave another error.
public User loginUser(String username, String password) {
TypedQuery<User> query = em.createQuery("Select u from User u " + "where u.username LIKE "
+ "?1 AND u.password LIKE " + "?2 AND u.delete =:delete", User.class);
query.setParameter(1, username);
query.setParameter(2, password);
query.setParameter("delete", false);
User foundUser = query.getSingleResult();
return foundUser;
}
It works with the other two u definitions u.username and u.password , but when I add u.delete it gives me this error. I expect it to return the object.
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/webproject] threw exception [java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u near line 1, column 101 [Select u from com.ikubinfo.project.model.User u where u.username LIKE ?1 AND u.password LIKE ?2 AND u.delete =:delete]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u near line 1, column 101 [Select u from com.ikubinfo.project.model.User u where u.username LIKE ?1 AND u.password LIKE ?2 AND u.delete =:delete]
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 org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:342)
at com.ikubinfo.project.repository.UserRepository.loginUser(UserRepository.java:34)
at com.ikubinfo.project.controller.UserResource.deleteUser(UserResource.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
delete cannot be used as property name, Please try to rename it?
Another option is to escape it in the entity class:
#Column(name = "\"delete\"")
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)"
i'm trying to execute this query :
Code:
this.getHibernateTemplate()
find("select distinct ci.customer " +
"from CustomerInvoice ci " +
"where ci.id in (?) " , ids);
with ids as a List, id is of type Long
when executing i get exception
Code:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Long
at org.hibernate.type.LongType.set(LongType.java:42)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:136)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:116)
at org.hibernate.param.PositionalParameterSpecification.bind(PositionalParameterSpecification.java:39)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:491)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1563)
at org.hibernate.loader.Loader.doQuery(Loader.java:673)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at org.springframework.orm.hibernate3.HibernateTemplate$29.doInHibernate(HibernateTemplate.java:849)
at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:372)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:840)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:836)
at
If you want to add a list to an in clause it is best to use a named parameter. This is done like so.
Query q = this.getHibernateTemplate().getSession().createQuery("select distinct ci.customer " +
"from CustomerInvoice ci " +
"where ci.id in (:idsParam) ");
q.setParameter("idsParam", ids);
List<Customer> = q.getResultList();
In addition to mR_fr0g's answer, this one also works:
this.getHibernateTemplate()
findByNamedParam("select distinct ci.customer " +
"from CustomerInvoice ci " +
"where ci.id in (:ids) ", "ids", ids);
You could use the Hibernate Criteria API, it has a so called "in" Restriction.
Reference:
Restrictions.in(String, Collection)
Btw. be aware of cases where the ids collection is empty! (not only if you use the criteria API)
You can use parameter list to inlcude in your query with 'IN' and 'setParameterList'
List<Long> ids= new ArrayList<Long>();
Query query = getSession().createQuery("select distinct ci.customer from CustomerInvoice ci where ci.id in (:ids) ");
query.setParameterList("ids", ids);
query.executeUpdate();
ProjectionList projList =
Projections.projectionList().add("customer","customer");
List<Long> ids = ids;
Criteria criteria = hibernateTemplate.getSessionFactory().getCurrentSession()
.createCriteria(CustomerInvoice.class)
.add(Restrictions.in("id",ids))
.setProjection(projList); List<Long> listOfIds = criteria.list();