【hibernate框架】核心开发接口-saveOrUpdate方法与delete方法

来源:互联网 发布:我的世界pc手机版js 编辑:程序博客网 时间:2024/06/06 03:04

1.saveOrUpdate方法剖析

saveOrUpdate方法:分情况看是save还是update。


示例:

public void testSaveOrUpdate(){Teacher t=new Teacher();t.setName("t21");t.setTitle("低级");t.setBrithday(new Date());t.setZhicheng(ZhiCheng.C);Configuration cfg=new Configuration();SessionFactory sf=cfg.configure().buildSessionFactory();Session session=sf.openSession();session.beginTransaction();session.saveOrUpdate(t);//这次是在数据库中添加了一个(即执行了save方法)session.getTransaction().commit();t.setTitle("高级");Session session2=sf.getCurrentSession();session2.beginTransaction();session2.saveOrUpdate(t);//这次是在数据库中修改了刚刚的数据(即执行了update方法)session2.getTransaction().commit();}


输出的Sql语句:
Hibernate: 
    insert 
    into
        _teacher
        (brithday, name, _title, zhicheng) 
    values
        (?, ?, ?, ?)
Hibernate: 
    update
        _teacher 
    set
        brithday=?,
        _title=?,
        zhicheng=? 
    where
        id=?

可以看出是先insert了teacher对象,之后update了数据库的teacher记录


2.delete方法

从表中删除相应的对象。

例子:删除表中id为4的对象

Teacher t=new Teacher();t.setId(4);t.setName("t11");t.setTitle("中级");t.setBrithday(new Date());t.setZhicheng(ZhiCheng.A);Configuration cfg=new Configuration();SessionFactory sf=cfg.configure().buildSessionFactory();Session session=sf.openSession();session.beginTransaction();session.delete(t);session.getTransaction().commit();session.close();sf.close();


必须有相应的ID,在缓存中和数据库中有才可以delete它。

这个不难,主要你自己取多做测试就行了

0 0
原创粉丝点击