Hibernate使用条件执行更新 [英] Hibernate execute update with criteria

查看:1076
本文介绍了Hibernate使用条件执行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hibernate 中使用 Criteria 时是否可以执行更新?例如:

Is it possible to execute an update while using Criteria in Hibernate? For example:

Session session = getSession();
Criteria crit = session.createCriteria(User.class);
crit.add(Restrictions.eq("token", sessionToken));

User user= new User();
Transaction tx = session.getTransaction();
try 
{
    tx.begin();
    session.updateWithCriteria(user, crit); //my imaginary function 
    tx.commit();
}
catch (Exception e) 
{
    e.printStackTrace();
    tx.rollback();
}

session.close();


推荐答案

有一个非常强大的功能叫做:

There is a very powerful feature called:

来自doc的小引用:


...但是,Hibernate提供了通过Hibernate查询语言执行批量SQL式DML语句执行的方法...

... However, Hibernate provides methods for bulk SQL-style DML statement execution that is performed through the Hibernate Query Language...

所以,虽然这不是关于 条件 - 我们仍然可以使用我们的域模型进行查询,因为它是关于的 HQL 即可。这是显示权力的片段:

So, while this is not about criteria - we still can use our domain model for querying, because it is about HQL. This is a snippet showing the power:

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 = s.createQuery( hqlUpdate )
        .setString( "newName", newName )
        .setString( "oldName", oldName )
        .executeUpdate();
tx.commit();
session.close();

摘要:准备就绪:


  • 我们可以使用查询来过滤结果

  • 我们可以对其应用批量更新

  • 我们不需要将这些行加载到内存中... ...

这篇关于Hibernate使用条件执行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆