Hibernate update request issue
For this update request
update TestDB.dbo.MyEmp set empname=? where empid=?
I wrote in my DAO class
MyEmployee myEmployee = new MyEmployee();
MyEmployee myEmployee =(MyEmployee )session.load(MyEmployee.class,
new Integer(1700));
myEmployee.setName("updatedName");
session.update(myEmployee );
Works great, but I need to know this update request mentioned below
update TestDB.dbo.MyEmp set empsalary=? where empid=? && empname = ?
(i.e. I need to update the table using two conditions in the where clause, this can be done using HQL, but I want to know how we can implement this using the saveOrUpdate method ..)
How can I perform an update using the update or saveOrUpdate () method? Is it possible to do this while sleeping?
source to share
You must first get your object in two ways:
1- HQL
Query query = session.createQuery("from MyEmployee e where e.id = ? and e.name = ?");
query.setParameter(0, 1);
query.setParameter(1, "myName");
MyEmployee e = (MyEmployee) query.uniqueResult();
e.setSalary(5000);
session.saveOrUpdate(e);
2- Criteria
Criteria criteria = session.createCriteria(MyEmployee.class);
criteria.add(Restrictionss.eq("id", 1)).add(Restrictions.eq("name", "myName");
MyEmployee e = (MyEmployee) criteria.uniqueResult();
e.setSalary(5000);
session.saveOrUpdate(e);
By the way, in default flash mode, when you fetch an object and update it, it will persist at the end of the session automatically (unless you are using StatelessSession).
source to share
Hibernate saveorupdate
will accept a table object, I mean the Pojo class as a parameter. Hibernate recognizes this object in the table by its primary key ie id.
This way, you don't need to add any other sentences containing the remaining parameters. Because you've already decided to keep the object independent of the data inside it.
If you really want to check for another parameter, you need to check it in java before saveorupdate
.
If you decide to keep all the object data, then only use saveorupdate
another wise option for HQL
or Criterias
for moreRestrictions
source to share