《Hibernate学习笔记五》Session 的update方法详解
在前面的学习中,我们用到了Session的save方法,将对象从tansient状态转化为persistent状态。下面我们就来学习Session的update方法。
在hibernate api文档中,Session接口提供了两种重载了update方法,分别如下:
1、void update(Object object) :Update the persistent instance with the identifier of the given detached instance.
此方法文档中的意思就是:根据唯一的标识将一个detached状态的对象更新为persistent状态。
第一个例子:detached状态的对象可以update
这个例子就是先new了一个对象,用session的save方法进行持久化,持久化后,对象进入到detached状态,之后我们进行更新操作,这样是可以更新的。
package com.hibernate.mode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.hibernate.model.Teacher;
public class TeacherTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass(){
sessionFactory = new Configuration().configure().buildSessionFactory();
}
@Test
public void testUpdate1() {
Session session=sessionFactory.getCurrentSession();
session.beginTransaction();
//新new的对象处于transient状态
Teacher t=new Teacher();
t.setName("wuranghao");
t.setTitle("professior");
session.save(t);
session.getTransaction().commit();
//commit之后,对象t就进入detached状态,下面我们用update方法对其进行更新
Session session2=sessionFactory.getCurrentSession();
session2.beginTransaction();
t.setName("haohao");
session2.update(t);
session2.getTransaction().commit();
}
@AfterClass
public static void afterClass(){
sessionFactory.close();
}
}
运行后在数据库中查询的结果如下,从结果可以看出,对象是更新成功了的。