@ Testpublic void persistent01Test () {Student student = new Student (); student. setStudentName ("James"); student. setAge (20); Session session = null; try {session = HibernateUtil. openSession (); session. beginTransaction (); session. save (student); session. getTransaction (). commit ();} catch (HibernateException e) {e. printStackTrace (); session. getTransaction (). commit ();} finally {HibernateUtil. closeSession (session );}}
Student changes from a temporary state to a persistent state. It can be found that both the database and session exist. The premise of a session existence is that the session is not closed,
SQL statement sent:
Hibernate: insert into t_student (student_name, age, student_id) values (?, ?, ?)
Example 3:
@ Testpublic void persistent02Test () {Student student = new Student (); student. setStudentName ("James"); student. setAge (20); Session session = null; try {session = HibernateUtil. openSession (); session. beginTransaction (); session. save (student); student. setStudentName ("aa"); session. getTransaction (). commit ();} catch (HibernateException e) {e. printStackTrace (); session. getTransaction (). commit ();} finally {HibernateUtil. closeSession (session );}}
After the save () method is called, the student object is converted to a persistent object and exists in the session. when the transaction is committed, hibernate compares the current sudent object with the sudent in the session.
If the two are different, the student object in the session will be synchronized to the database and the update statement will be sent. The two are the same and will not be processed.
Send SQL statement:
Hibernate: insert into t_student (student_name, age, student_id) values (?, ?, ?)Hibernate: update t_student set student_name=?, age=? where student_id=?
Example 4:
@ Testpublic void persistent04Test () {Student student = new Student (); student. setStudentName ("James"); student. setAge (20); Session session = null; try {session = HibernateUtil. openSession (); session. beginTransaction (); session. save (student); student. setStudentName ("aa"); session. update (student); student. setAge (55); session. update (student); session. save (student); session. save (student); session. getTransaction (). commit ();} catch (HibernateException e) {e. printStackTrace (); session. getTransaction (). commit ();} finally {HibernateUtil. closeSession (session );}}
If a Persistent Object finds a change, calling update () or save () multiple times is invalid. It is synchronized to the database only when the transaction is committed and an update statement is sent.
Send SQL statement:
Hibernate: insert into t_student (student_name, age, student_id) values (?, ?, ?)Hibernate: update t_student set student_name=?, age=? where student_id=?