1.三种对象状态
比如这个测试
@Test
public void TestSave()
{
Teacher stu=new Teacher();
stu.setTitle("high");
stu.setName("wanhao");
SessionFactory sf=new AnnotationConfiguration().configure().buildSessionFactory();
Session sess=sf.getCurrentSession();
sess.beginTransaction();
System.out.print("1:"+stu.getId());
sess.save(stu);
System.out.print(stu.getId());
sess.getTransaction().commit();
System.out.print("3:"+stu.getId());
}
save()之前为transient对象。
save()之后到commit()之间为 persistent 对象。
commit()后为detached(托管的)对象。
2.Session还可以通过id删除数据库数据,只要有id属性便可
Teacher stu=new Teacher();
stu.setId(1);
SessionFactory sf=new AnnotationConfiguration().configure().buildSessionFactory();
Session sess=sf.getCurrentSession();
sess.beginTransaction();
sess.delete(stu);
sess.getTransaction().commit();
3.获取数据库对象
可以用Session的get方法,也有load方法,使用的格式一样。
实例代码:
SessionFactory sf=new AnnotationConfiguration().configure().buildSessionFactory();
Session sess=sf.getCurrentSession();
sess.beginTransaction();
Teacher st=(Teacher) sess.get(Teacher.class, 3);
sess.getTransaction().commit();
其中3表示id为3。
4.更新数据库对象,使用到update方法
经常使用三个方法:
第二种方法不适合于Annotation,所以不推荐。
而第一种方法当设置了不可更新,则不能重新设置这个属性,有很大局限性。
实际中,可以直接先用update测试下,若是效率可以接受,就省去一大堆操作,数据库内部也有优化,即使全部更新或许也可以满足要求。
HQL语句未完待续。。。。。。