Anand
Anand

Reputation: 21338

updating some column values in hibernate

I have a table in which there are 14 columns. Now I have a object corresponds to the table in which I have only 5 values to be updated.
I am using saveOrUpdate method to either save/update the row. The issue is that when I use this method to update those 5 columns, all other 9 column values are set to null.
One solution is that I write update sql query to do the same but I want to use Hibernate API's not sql queries.
Is there any way to achieve that?

Upvotes: 2

Views: 18733

Answers (4)

Rakib Hasan
Rakib Hasan

Reputation: 21

Add @DynamicUpdate annotation on your entity class

@Entity
@DynamicUpdate
public class Product implements Serializable {

//rest of the codes are omitted for brevity

}

then update specific column (or columns) value of the table

Product newProduct = session.get(Product.class, id);//here id is the product_id for which you are gonna update
newProduct.setName("Pencil 2B");//new name
session.update(newProduct);

@DynamicUpdate will update only the modified column(s), rest of the columns won't be affected.

Upvotes: 0

Ashok Parmar
Ashok Parmar

Reputation: 408

Using Hibernate 5 try below code....

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaUpdate<Vehicle> criteria = builder.createCriteriaUpdate(Vehicle.class);
Root<Vehicle> root = criteria.from(Vehicle.class);
criteria.set(root.get("ownername"), "Ashok Parmar");
criteria.where(builder.equal(root.get("vehicleId"), "123"));
session.createQuery(criteria).executeUpdate();

Upvotes: 0

Nguyen Tan Hung
Nguyen Tan Hung

Reputation: 59

Use DynamicUpdate on Entity

Example:

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

SQL will be like;

Hibernate:
    update
        mkyong.stock_transaction
    set
        VOLUME=?
    where
        TRAN_ID=?

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

Foo objectToUpdate = (Foo) session.get(Foo.class, idOfObjectToUpdate);
objectToUpdate.setField1(newValue1);
objectToUpdate.setField2(newValue2);

No need to call saveOrUpdate() or merge(): the object is attached, so everything is flushed and committed at the end of the transaction.

Upvotes: 9

Related Questions