problem with HQL update - java

When I try to execute the following HQL query:
Query query = getSession().createQuery("update XYZ set status = 10");
query.executeUpdate();
I get this exception:
Exception in thread "main" org.hibernate.QueryException: query must begin with SELECT or FROM: update
EDIT:
I also tried following .But it doennot work either.
org.hibernate.Query query = getSession().createQuery("update XYZ t set t.status = 10");
EDIT2:
Making changes in hinbernate.cfg.xml solved my problem
Earlier i was using
setting hibernate.query.factory_class" = org.hibernate.hql.classic.ClassicQueryTranslatorFactor
Now am using following property
<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>

Thats not an HQL query.
You want to import javax.persistence.Query which allows normal sql,
not org.hibernate.Query which works on entity objects.
If you want to use simple sql, you could also use PreparedStatement
However, if you really want to use hibernate, without taking advantage of entityobjects (totally defeating the point of using hibernate in the first place, imho) you could do it like this (reference docs):
String myUpdate = "update XYZ myAlias set myAlias.status = :newStatus";
// or String noAliasMyUpdate = "update XYZ set status = :newStatus";
int updatedEntities = getSession().createQuery(myUpdate) //or noAliasMyUpdate
.setInt( "newStatus", 10 )
.executeUpdate();

The question is thinking in SQL, when you should be thinking in objects:
XYZ xyz = new XYZ();
xyz.setStatus(10);
getSession().merge(xyz);

Try:
Query query = getSession().createQuery("update XYZ o set o.status = 10");
query.executeUpdate();
Take a look at this also.

Session sesssion = getSession(); //getter for session
For HQL :
String hql = "update Activity " +
"set startedOn = :taskStartedOn " +
"where id = :taskId";
Query query = session.createQuery(hql);
query.setDate("taskStartedOn",new Date());
query.setLong("taskId",1)
int rowCount = query.executeUpdate();
Here Activity is POJO.

Use
hibernate.query.factory_class = org.hibernate.hql.ast.ASTQueryTranslatorFactory
in hibernate.cfg.xml file to resolve exception:
org.hibernate.QueryException: query must begin with SELECT or FROM: update.....

Related

JPA - Select All Rows from Dynamic Table Name

Hi guys I am new to jpa, named queries, etc.. and I need something like this:
select t from :tableName t
Later in code I want something like this:
em.createQuery(...);
setParameter("tableName", "Person")
Result would be:
select * from person
How to write such a generic jpa query statement allowing to select all rows from :tableName which may be defined at runtime? thanks in advance
Try this I think this works well
EntityManagerFactory emfactory=Persistence.createEntityManagerFactory("Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager();
Query query = entitymanager.
createQuery("Select p from Person p");
List<String> list = query.getResultList();
setParameter("foo", foo) is used to set the value for column of the table not to set the table name. I do not think it will work, as you want to set the table name dynamically.
You can try this:
public returnType foo(String tableName){
String jpql = "SELECT t FROM " + tableName+ " t";
Query query = em.createQuery(jpql);
//rest of the code
}

Pass the dynamically created query (according to condition) in #Query annotation

I am using the #Query annotation to execute the query in spring repository.
But I want to change the some part or make a new query according to the condition and pass in the #Query("pass here the query according to condition")
This is my query
#Query("SELECT ds.symptom FROM DoctorSymptomsModel ds where ds.doctorId = :doctorId and ds.isMostUsed = :isMostUsed)
If some condition satisfy then concat the "ORDER BY createdDate" part in query.
Or
Can I make the variable and set the query in that variable and set like that
String query = SELECT ds.symptom FROM DoctorSymptomsModel ds where
ds.doctorId = :doctorId and ds.isMostUsed = :isMostUsed
if(result){
query = SELECT ds.symptom FROM DoctorSymptomsModel ds where ds.doctorId =
:doctorId and ds.isMostUsed = :isMostUsed ORDER BY createdDate
}
//pass the query variable here
#Query(query)
List<String> findDoctorSymptomsModelList(#Param("doctorId") long doctorId,
#Param("isMostUsed") boolean isMostUsed);
To make a dynamic query, you should think about CriteriaQuery. Take a look at this link for brief introduction.

Not able to fetch resultset in Hibernate using HQL

I'm triggering a query using HQL, normally it should return empty resultset as it doesn't have any records w.r.t it. But, it throws
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
My code is
String hql = "FROM com.pck.Person where userId = " + userId;
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<Dashboard> listUserDetails = query.list(); <-- Problem here.
I'm expecting list size is 0 because there are no records w.r.t userId passed.
What changes do I need to do?
Lets say the value of userId was "abc12"
Given your code, the value of the string called hql would become:
"FROM com.pck.Person where userId = abc12"
If you took the value of that string and tried to run it as a query on any database, most of them would fail to understand that abc12 is a string. Normally it would be interpreted as a variable.
As other users mentioned including the single quotes would produce the desired query, but the recommended way to assign parameter values is this:
String hql = "FROM com.pck.Person where userId = :id"
query.setParameter("id", userId);
Looks like you are missing single quotes around userid.
Try with "FROM com.pck.Person where userId = '" + userId + "'";
or
Use named parameters with query.setParameter("userid", userId);
Posting the full stacktrace would help if this doesn't solve.

How can I add a value to a column?

I want to add a value to an existing column, but I don't want to have to select it first. Right now I would have to do something like
// run hql in a named query
from Employee where id = :id
// after running the above
e.setBonus(e.getBonus() + 100); // add 100 to e's bonus
// commit to database
HibernateUtil.saveOrUpdate(e);
But I want something that's just one-and-done - something like
update Employee e set e.bonus = e.bonus + 100
Is this something I can do in Hibernate? If so, how. If not, what's the suggested best practice for such an update?
You could create a hql query that just does an update
Query updateBonus = createQuery("UPDATE Employee SET bonus = bonus+100 WHERE id = :id" );
updateBonus.setInteger("id", employee.getId());
updateBonus.executeUpdate();
Yes, you can do it as intended with hql query. Try such code:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hql="update Employee e set e.bonus = e.bonus + :p where id=:id";
session.createQuery(hql).setInteger("p",100).setInteger("id",id).executeUpdate();
tx.commit();
session.close();
More info you can find by the link

Hibernate Exception while executing query

Following is my code snippet:
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/applicationContext*.xml");
JpaTransactionManager jpatm = (JpaTransactionManager) ctx
.getBean("transactionManager");
EntityManager em = jpatm.getEntityManagerFactory()
.createEntityManager();
String sqlQuery = "SELECT suc FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", parentid);
ArrayList<SubUsrCont> listContent = (ArrayList<SubUsrCont>) query.getResultList();
But when ever executed I get the following error:
[http-8080-1] ERROR org.hibernate.hql.PARSER - line 1:92: expecting OPEN, found '.'
Can anybody help???
Well, I found it and successfully tested it as well. It was due to my POJO package name. Previously it was in.myproject.myname. I changed it to com.myproject.myname. HQL was taking in as the SQL Keyword IN and was looking for OPEN '('.
Why are you using a Native SQL query inside em.createQuery()? This will not work because HQL can not have SELECT and furthermore you don't set the value for parameter :parentuserid.
String sqlQuery = "FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", <PARENT USER ID TO BE SEARCHED>);
Try this and see
If you would like to execute SQL use createNativeQuery. Also try "SELECT suc.* ...
Also you don't set the parameter :parentuserid
Use query setParameter("parentuserid",someValue)

Categories