我有一个包含mamy列的表,我想在不影响其余列的情况下更新该行的一列或几列
我可以写查询:
update table as t set t.a=:a set t.b=:b where t.id=1
但是看到我不知道将选择要更新的列,并且我认为为每种情况编写每个查询不是一个好主意。好了,我必须为每种情况编写查询,但是我正在寻找一种更好的方法来动态更新表。我认为标准将是一个不错的选择。但是问题是我不知道如何编写标准更新特定列。我的代码现在可以更新该列,但是它将其他列设置为null或为空。
在不更改其他列的情况下更新特定列的好方法是什么?
最佳答案
Hibernate支持两种基本方法来更新表的列。
第一种是自然的,通过将实体加载到session
,在运行时对其进行更改,然后将更改刷新(udpate)回数据库。这是标准的ORM样式。
第二个主要针对非常高效的SQL UPDATE 语句。它在此处记录为:
15.4. DML-style operations
从文档中引用:
... However, Hibernate provides methods for bulk SQL-style DML statement execution that is performed through the Hibernate Query Language...
它不提供用于条件查询的API,但在我们的域模型中可以与HQL ==一起使用。
我们可以在映射实体的顶部创建WHERE子句,并仅选择几列进行更新。有一些限制(不支持JOIN),但是可以通过子查询解决...
这是doc的摘录:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = session.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
还要检查以下问答:Hibernate execute update with criteria
关于 hibernate 使用条件更新单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245881/