《Hibernate学习笔记五》Session 的update方法详解

《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();
    }

    }

运行后在数据库中查询的结果如下,从结果可以看出,对象是更新成功了的。

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值