I'm using Hibernate and I want to make a bulk update, changing the status of all objects within a list of ids.
So I tried:
String update = "UPDATE Foo as foo SET foo.status = :status WHERE foo.id in (:idList)"
Which caused an exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax;
I also tried:
String update = "UPDATE Foo as foo SET foo.status = :status WHERE foo.id in (SELECT id FROM Foo WHERE id in (:idList))"
That caused the same exception.
I'm inserting the parameters like this:
StatelessSession ss = sessionFactory.openStatelessSession();
Query query = ss.createQuery(update);
query.setParameter("status", status);
query.setParameterList("idList", ids);
query.executeUpdate();
Any ideas how to make this work?
Thanks in advance
Status is a MySQL reserved word. Rename your column to something else
Related
I'm using Hibernate in my project and using "Query" Like below.
Query query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
I'm getting the result. When i'm using generics Like below
Query<?> query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
getting the result because "?" is something as wildcard (or) it will accept any datatype
when i'm using the code as below getting some error( java.lang.IllegalArgumentException: Update/delete queries cannot be typed ). i'm using Integer datatype because createQuery return number when it's executed
Query<Integer> query = em.createQuery("delete from User where name=:name", Integer.class);
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
Any suggestions. I have to use Generics with specific datatype in it like above code.
thanks in advance
Unfortunately executeUpdate does not allow you to use a typed query.
Instead you can use uniqueResult, and cast to the type that you want:
Query query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = (Integer) query.uniqueResult();
Referencing this answer
SQL statement:
UPDATE table SET column = 'new_value' WHERE column = 'old_value'
(same column name)
How to do this in Hibernate?
You may use EntityManager.merge() which can lead to NonUniqueObjectException if there are multiple results are found with same column name.
Better to use NamedQuery ot NativeNamedQuery to achieve this.
My understanding is that you would want to perform batch updates.
I suggest you refer to this link
You can make use of the below code in order to get this done.
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
Do note the below point mentioned in the link.
Joins, either implicit or explicit, are prohibited in a bulk HQL query. You can use sub-queries in the WHERE clause, and the sub-queries themselves can contain joins.
I have two entities Like SmsOut and SmsIn. The relation between two entities contains OneToMany where smsIn.id is primary key and smsOut.sms_in_id is foreign key.
Now I want to pass parameter like smsIn.mobileNumber, smsIn.smsText and so on, on the query
SELECT so FROM SmsOut so order by id desc
Following is my database diagram:
Edited
Following is my code :
String sql = "SELECT so FROM SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc";
Query query = em.createQuery(sql);
query.setParameter("mobileNumber", mobileNumber);
query.setParameter("smsText", smsText);
query.setParameter("shortCode", shortCode);
query.setParameter("smsOutDate", startDate);
query.setParameter("smsOutDate", endDate);
smsOutList = query.getResultList();
and exception is :
SEVERE: line 1:188: expecting "and", found '='
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: expecting "and", found '=' near line 1, column 188 [SELECT so FROM com.f1soft.SMSC.entities.SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:624)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:96)
Please Help me.
Thanks
You haven't explained the JPA relationship between SmsIn and SmsOut, so I'll assume SmsOut has a getSmsIn() with a relation on the id field.
When you have an EntityManager em, you can call em.createQuery, which is like SQL prepare, and then setParameter:
TypedQuery<SmsOut> q = em.createQuery("SELECT so FROM SmsOut so WHERE so.smsIn.mobileNumber = :number ORDER BY id DESC");
q.setParameter("number", "12345678");
List<SmsOut> results = q.getResultList();
See the Javadoc for Query for the different ways you can specify the parameters.
SELECT so FROM SmsOut so WHERE smsIn.mobileNumber = ? AND smsIn.smsText =? order by id desc
Replace the ? sign with the apropiate values.
between is the problem:
between so.smsOutDate =:startDate and so.smsOutDate =:endDate
try
so.smsOutDate between =:startDate and =:endDate
This simple query
session = com.jthink.songlayer.hibernate.HibernateUtil.getSession();
Query q = session.createQuery("recNo from SongChanges");
giving this stacktrace
java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:63)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:272)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:119)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:214)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:192)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1537)
if I do
session = com.jthink.songlayer.hibernate.HibernateUtil.getSession();
Query q = session.createQuery("from SongChanges");
I dont get the error, but I only need the recNo
Any ideas ?
You forgot the select:
Query q = session.createQuery("select sc.recNo from SongChanges sc");
This error also commonly happens when you use the method createQuery to run a named query, instead of getNamedQuery, for example:
session.createQuery("InvoiceItem.itemsFromInvoice")
when the correct approach would be
session.getNamedQuery("InvoiceItem.itemsFromInvoice")
The SELECT clause provides more control over the result set than the from clause. If you want to obtain few properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of using SELECT clause to get just name field of the Employee object:
String hql = "SELECT E.name FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();
If you want whole object that time "select * from" is not needed.
When i use alias for column i get error. Without alias everytinig works good. What is the problem with that ? This is simple example, but need to use more aliases in real project to wrap results in some not-entity class, but can't because of this error. How to solve this ?
NOT WORKING (with alias on id column):
public List<Long> findAll(Long ownerId) {
String sql = "select id as myId from products where ownerId = "+ownerId;
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
}
Error:
WARN [JDBCExceptionReporter:77] : SQL Error: 0, SQLState: S0022 ERROR
[JDBCExceptionReporter:78] : Column 'id' not found.
WORKING (without alias):
public List<Long> findAll(Long ownerId) {
String sql = "select id from products where ownerId = "+ownerId;
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
}
If your "product" is mapped, hibernate probably don't know about "myId" and therefore can't select it.
You can try something like:
getSession().createSQLQuery(sql).addScalar("myId", Hibernate.LONG)