Sunny
Sunny

Reputation: 33

How can I update a row based on id in hibernate

I am new in hibernate. I am using SesssionFactory to get the session of the transaction and one way which I found after searching is used for setting few fields using set parameter i.e

Query query = getCurrentSession().createSQLQuery(
    "UPDATE table_name set field1=:f1 where ID=:id");

query.setParameter("f1", f1);
query.setParameter("id", id);

but I want to update the whole row. I have already set the values in the entity class but is there a way to pass the values of the whole entity class to the database based on the id the id is the primary key for the table which I want to update.

Upvotes: 3

Views: 19738

Answers (3)

Thamiar
Thamiar

Reputation: 610

To be as OO as you can, you can get entity by session.get(entityClass, id); And then after modifying object by setters/getters, you can save it back to the DB using update method :session.update(entity);

Upvotes: 0

PA001
PA001

Reputation: 451

Take a look at Session#update (or saveOrUpdate). This will allow you to persist a complete, mapped, object to the database.

Upvotes: 0

Oliver Meyer
Oliver Meyer

Reputation: 88

you already have all data present in the hibernate entity object? Then just call the session directly:

getCurrentSession().save(myEntity);

to create a new object, or

getCurrentSession().update(myEntity);

to update an existing row.

If not sure, you can use:

getCurrentSession().saveOrUpdate(myEntity);

Upvotes: 6

Related Questions