Hibernate persists the entity using save and then changes the value of the entity
Public static void addStudent () {sessionFactory=new AnnotationConfiguration (). Configure (). BuildSessionFactory (); Session session=sessionFactory.getCurrentSession (); session.beginTransaction (); Student student=new Student ("Li Si", 34); session.save (student); student.setName ("Wang Wu"); Iterator iterator= (Iterator) session.createQuery ("from Student"). Iterate () While (iterator.hasNext ()) {System.out.println (iterator.next (). ToString ());} session.getTransaction () .commit ();}
Be careful
Session.save (student); student.setName (Wang Wu)
After session persists the entity, it is only written to the session cache. It is not written to the database before commit. Change it at this time.
Entities, the entities saved to the database are modified entities.
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 iterator= (Iterator) session.createQuery ("from Student"). Iterate () While (iterator.hasNext ()) {System.out.println (iterator.next (). ToString ());} session.getTransaction () .commit ();}
After finding the record with id 2 from the database, there is an entity in the session cache, and the value of the entity is modified directly. After the record is not submitted by update,session, the record in the database is still modified.
For query first and then modify
Do not write update,merge and
Session.update (student)
Session.merge (student)
It's all the same. After commit, all the data will be written to the database.
Student student=new Student (10, "update", 100) session.update (student)
Directly new an entity (its id=10 record does not exist in the database), and report an error directly by update
Org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
The id of this Student object is set to augment, and the record of its id=10 does not exist in the database
Student student=new Student (10, "update", 100) session.merge (student)
As a result, the database keeps records, but the id is not 10, but 6 as a result of self-increment (the maximum is 5 before insertion).
Student student=new Student (11, "update", 100); session.saveOrUpdate (student)
However, saveOrUpdate (), which imagined that this operation could be done, also reported an error.
Org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1Hibernate: update Student set age=?, name=? Where id=?
The sql sent out is update, why not save, it should be selected automatically.