public void testUpDate1(){ Configuration cfg=new Configuration(); SessionFactory sf=cfg.configure().buildSessionFactory(); Session session=sf.openSession(); session.beginTransaction(); Teacher teacher=(Teacher)session.get(Teacher.class, 1); session.getTransaction().commit(); teacher.setName("mr.zhang"); Session session2=sf.openSession(); session2.beginTransaction(); session2.update(teacher); session2.getTransaction().commit(); }
public void testUpDate2(){ //这样更新Transient(游离状态)对象会报错 /*Teacher teacher=new Teacher(); teacher.setName("mr.liu"); Configuration cfg=new AnnotationConfiguration(); SessionFactory sf=cfg.configure().buildSessionFactory(); teacher.setName("mr.zhang"); Session session2=sf.openSession(); session2.beginTransaction(); session2.update(teacher); session2.getTransaction().commit();*/ //给他设置id,只要数据库中有,就会更新Transient(游离状态) Teacher teacher=new Teacher(); teacher.setId(8); teacher.setName("mr.liu"); Configuration cfg=new AnnotationConfiguration(); SessionFactory sf=cfg.configure().buildSessionFactory(); teacher.setName("mr.zhang"); Session session2=sf.openSession(); session2.beginTransaction(); session2.update(teacher); session2.getTransaction().commit(); }
public void testUpDate3(){ Configuration cfg=new AnnotationConfiguration(); SessionFactory sf=cfg.configure().buildSessionFactory(); Session session=sf.openSession(); session.beginTransaction(); Teacher teacher=(Teacher)session.get(Teacher.class, 1); teacher.setTitle("高等"); session.getTransaction().commit(); }在get出teacher对象时它发出了一条update语句,原因是我们改了它的name了。因为修改数据了,所以在提交(commit();)时,session会检查缓存和数据库的同步情况,当不同步时,就更新数据库至两者同步。不幸的是还是更新了所有字段。
@Column(updatable=false) public String getName() { return name; }在不需要更新的字段或字段的get方法上加Column(updatable=false)注解即可。
public void testUpDate4(){ Configuration cfg=new AnnotationConfiguration(); SessionFactory sf=cfg.configure().buildSessionFactory(); Session session=sf.openSession(); session.beginTransaction(); StudentPK sp=new StudentPK();//联合主键 sp.setId(2); sp.setName("s2"); Student student=(Student)session.get(Student.class, sp); student.setAge(100);//只更新年龄 session.getTransaction().commit(); }这里看到hibernate发出的sql语句只更新了一个属性:
public void testUpDate5(){ Configuration cfg=new AnnotationConfiguration(); SessionFactory sf=cfg.configure().buildSessionFactory(); Session session=sf.openSession(); session.beginTransaction(); //HQL面向对象的查询语言,此时就只会更新name自己 Query q=session.createQuery("update Teacher t set t.name = 't22' where t.id = 2"); q.executeUpdate(); session.getTransaction().commit(); }观察hibernate发出的sql语句确实如此,很方便。记住,HQL是面向对象的SQL语句。
总结:你要觉得全更新字段效率可以不考虑,就可以不去理会它(说不定数据库中也会进行优化,没改的它就不改了)。
转载请注明出处:http://blog.csdn.net/acmman