DML更新及删除
示例:
package com.bjsxt.hibernate;
import junit.framework.TestCase;
import org.hibernate.Query;
import org.hibernate.Session;
public class DMLQueryTest extends TestCase {
public void testQuery1() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
/**
* 使用这种风格的操作,将会造成内存中的对象与数据库中的数据不同步,所以
* 建议尽量少使用:因为hibernate有一级缓存,而更新不更新缓存的数据,只是更新了数据库的数据。
* 应尽量用hibernate的update操作
*/
Query updateQuery = session.createQuery("update Student a set a.name=? where a.id in(:ids)");
updateQuery.setParameter(0, "张三");
updateQuery.setParameterList("ids", new Object[]{1, 2});
updateQuery.executeUpdate();
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}
public void testQuery2() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
// Query updateQuery = session.createQuery("delete from Student s where s.id='1'");
Query updateQuery = session.createQuery("delete from Student s where s.id=?").setParameter(0, 2);
updateQuery.executeUpdate();
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}
}
我们要更新数据或删除数据,一般会先通过load/get/list查询等使对象进入持久状态,然后直接调用set方法更改属性,hibernate会自动发出一条更新语句进行更新操作。如
public void testQuery3() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
List list = session.createQuery("select s from Student s where s.id=3").list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Student object = (Student) iterator.next();
System.out.println(object.getName());
object.setName("yeyeyeye");
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}
上例中查询出来的name值的Student对象进入持久状态,马上调用了setName方法执行时的sql:
Hibernate: select student0_.id as id1_, student0_.name as name1_, student0_.createTime as createTime1_, student0_.classid as classid1_ from t_student student0_ where student0_.id=3
gooooeeeeood
Hibernate: update t_student set name=?, createTime=?, classid=? where id=?
上面:gooooeeeeood为原来的name值,再次查询数据库时name变成了yeyeyeye