Hibernate execute update with criteria

48,210

Solution 1

There is a very powerful feature called:

15.4. DML-style operations

small cite from doc:

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

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();

SUMMARY: Having that in place:

  • we can use query to filter results
  • we can apply bulk update on it
  • we won't need to load these rows in memory, into the session...

Solution 2

Now we can do something like this for bulk update and delete. New api's released for criteriaUpdate and CriteriaDelete

CriteriaBuilder cb = this.em.getCriteriaBuilder();
// create update
CriteriaUpdate<Order> update = cb.createCriteriaUpdate(Order.class);
// set the root class
Root e = update.from(Order.class);
// set update and where clause
update.set("amount", newAmount);
update.where(cb.greaterThanOrEqualTo(e.get("amount"), oldAmount));
// perform update
this.em.createQuery(update).executeUpdate();

Solution 3

First you should get the object then modify and update:

   Query q = session.createQuery("from StockTransaction where tranId = :tranId ");
   q.setParameter("tranId", 11);
   StockTransaction stockTran = (StockTransaction)q.list().get(0);

   stockTran.setVolume(4000000L);
   session.update(stockTran);

If you want to use partial/dynamic update feature then put

@org.hibernate.annotations.Entity(
        dynamicUpdate = true
)

annotation on top of the dao class.

Example from: http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/

Note: The Question is "with criteria" but the accepted answer is NOT "with criteria" but SQL.

Share:
48,210
vlio20
Author by

vlio20

Updated on January 15, 2020

Comments

  • vlio20
    vlio20 over 4 years

    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();
    
  • usr-local-ΕΨΗΕΛΩΝ
    usr-local-ΕΨΗΕΛΩΝ almost 7 years
    Summary: it is not possible to run a DML using Criteria
  • Alex von Brandenfels
    Alex von Brandenfels about 6 years
    What is the variable s?
  • hrk singh
    hrk singh over 3 years
    can you explain more clearly how this query translates to normal SQL query for reference
  • Guerino Rodella
    Guerino Rodella over 3 years
    Is it needed to start the transaction before call executeUpdate() ? Or it's not?