public static void addStudent(){ sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory(); Session session=sessionFactory.getCurrentSession(); session.beginTransaction(); Student student=new Student( "李四", 34); session.save(student); student.setName("王五"); Iterator<Student> iterator=(Iterator<Student>) session.createQuery("from Student").iterate(); while(iterator.hasNext()){ System.out.println(iterator.next().toString()); } session.getTransaction().commit(); }
注意java
session.save(student); student.setName("王五");
session持久化了實體後,只是寫入了session緩存中,commit前並無寫入數據庫中,此時再改變sql
實體,保存到數據庫的實體爲修改過的實體。數據庫
public static void updateStudent(){ sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory(); Session session=sessionFactory.getCurrentSession(); session.beginTransaction(); Student student=(Student) session.get(Student.class, 2); student.setName("update"); Iterator<Student> iterator=(Iterator<Student>) session.createQuery("from Student").iterate(); while(iterator.hasNext()){ System.out.println(iterator.next().toString()); } session.getTransaction().commit(); }
從數據庫中查找id爲2的記錄後,此時session緩存中有了實體,直接修改實體的值,不用update,session提交後,數據庫的記錄依然被修改了緩存
對於先查詢再修改,session
不寫update,merge和ide
session.update(student);ui
session.merge(student);hibernate
都是同樣的,commit後數據都會寫入數據庫3d
Student student=new Student(10,"update", 100); session.update(student);
直接new一個實體(其id=10的記錄在數據庫中不存在),直接update報錯對象
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
此Student對象的id設置了自增,其id=10的記錄在數據庫中不存在,
Student student=new Student(10,"update", 100); session.merge(student);
結果數據庫保存了記錄,可是id不爲10,而是按照自增的結果,爲6(插入前最大爲5)
Student student=new Student(11,"update", 100); session.saveOrUpdate(student);
而想象中能夠完成此操做的saveOrUpdate()卻也報錯
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
Hibernate: update Student set age=?, name=? where id=?
發出的sql居然是update,怎麼不是save,應該是自動選擇纔對?