vlio20
vlio20

Reputation: 9295

Hibernate execute update with 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();

Upvotes: 15

Views: 54741

Answers (3)

Payal Bansal
Payal Bansal

Reputation: 755

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

Upvotes: 13

Ismail Yavuz
Ismail Yavuz

Reputation: 7045

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.

Upvotes: 1

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

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...

Upvotes: 13

Related Questions