Hibernate update single column using criteria

I have a table containing mamy columns, and I want to update one or more columns of a row without executing the remaining columns. I can write a query:

update table as t set ta=:a set tb=:b where t.id=1 

But I saw that I do not know which columns will be selected for the update, and I think that it is not worth writing each query for each scenario. Well, I have to write a query for each scenario, but I'm looking for the best way to dynamically update a table. I think the criteria would be a good choice. But the problem is that I have no idea how to write criteria for updating a specific column. My code can now update a column, but it would set the other column to null or empty.

What would be a good way to update certain columns without changing other columns?

+7
source share
3 answers

Hibernate supports two main ways to update table columns.

The first is natural, loading the object into session , changing it at runtime, discard (post) the changes back to the database. This is the standard ORM style.

The second is mainly focused on a very efficient SQL UPDATE statement . It is described here as:

15.4. DML style operations

reference doc:

... However, Hibernate provides methods for mass executing a SQL-style DML statement executed using the Hibernate query language ...

It does not provide an API for querying criteria, but it works with HQL == with our domain model.

We can create a WHERE clause on top of our mapped objects and request an update from only the few columns that we have selected. There are some restrictions (JOIN is not supported), but they can be solved by subqueries ...

This is a fragment of a doc document:

 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 out this Q & Q: Hibernate upgrade with criteria

+13
source

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(); 
+5
source

.setString( "newName", newName ) - deprecated, new method below!

 int updatedEntities1 = session.createQuery( hqlUpdate ) .setParameter("column_name", value) .executeUpdate(); 
0
source

Source: https://habr.com/ru/post/976390/


All Articles