hibernate update single column using criteria

别说谁变了你拦得住时间么 提交于 2019-12-05 04:52:33
Radim Köhler

Hibernate supports two basic ways how to update tables' columns.

The first is natural, via loading entity into session, changing it in run-time, flush (udpate) the changes back to DB. This is a standard, ORM style.

The second is mostly oriented on very efficient SQL UPDATE statement. It is documented here as:

15.4. DML-style operations

cite from doc:

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

It does not provide API for criteria query, but it does work with HQL == with our domain model.

We can create a WHERE clause on top of our mapped entities, and ask for update only of a few columns, we selected. There are some limitations (JOIN is not supported) but they can be solved by subqueries...

This is a snippet from 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();

Also check this Q&Q: Hibernate execute update with criteria

Using JPA you can do it this way.

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaUpdate<User> criteria = builder.createCriteriaUpdate(User.class);
Root<User> root = criteria.from(User.class);
criteria.set(root.get("fname"), user.getName());
criteria.set(root.get("lname"), user.getlastName());
criteria.where(builder.equal(root.get("id"), user.getId()));
session.createQuery(criteria).executeUpdate();

.setString( "newName", newName )-- is Deprecated, The new method is below!

int updatedEntities1 = session.createQuery( hqlUpdate )
                    .setParameter("column_name", value)
                    .executeUpdate();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!