问题
For this update query
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 );
Its working fine, but I need to know for this type of update query mentioned in below
update TestDB.dbo.MyEmp set empsalary=? where empid=? && empname = ?
(i.e., I need to update the table by using two conditions in where clause , this can be done by HQL , but i want to know how can we implement this by using saveOrUpdate method..)
How I can do update by using update or saveOrUpdate method()? Whether its possible to do like that in hibernate ?
回答1:
You must fetch your object first, 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 flush mode, when you fetch the object, and update it, it will be persisted at the end of session automatically (if you are not using StatelessSession).
回答2:
Hibernate saveorupdate
will take table entity ,I mean Pojo class as a parameter .Hibernate will recognize that entity in table by its primary key i.e id .
So you need not to add any other where clauses on with remaining parameters ..because you are already decided to save the entity regardless of data inside it .
If you really want to check the other parameter you have to check the same in java it self before Saveorupdate
.
If you decided to save the whole Object data then and then only use saveOrUpdate
other wise go for HQL
or Criterias
for more Restrictions
来源:https://stackoverflow.com/questions/14723528/hibernate-update-query-issue