简体   繁体   English

休眠更新同列

[英]Hibernate update with same column

SQL statement: SQL语句:

UPDATE table SET column = 'new_value' WHERE column = 'old_value'

(same column name) (相同的列名)

How to do this in Hibernate? 在Hibernate中如何做到这一点?

You may use EntityManager.merge() which can lead to NonUniqueObjectException if there are multiple results are found with same column name. 您可以使用EntityManager.merge(),如果找到多个具有相同列名的结果,则可能导致NonUniqueObjectException。

Better to use NamedQuery ot NativeNamedQuery to achieve this. 最好使用NamedQuery或NativeNamedQuery来实现此目的。

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. 批量HQL查询中禁止使用隐式或显式联接。 You can use sub-queries in the WHERE clause, and the sub-queries themselves can contain joins. 您可以在WHERE子句中使用子查询,并且子查询本身可以包含联接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM