代碼:
private static void editInfo() {
Session session = null;
try {
session = HibernateUtil.getSession();
if (session != null) {
session.beginTransaction();
Person p = new Person("王三", 22, "男", "北京");
session.save(p);
session.delete(p);
p.setId(null);
session.save(p);
session.getTransaction().commit();
}
} catch (Exception ex) {
if (session != null) {
session.getTransaction().rollback();
}
ex.printStackTrace();
} finally {
HibernateUtil.CloseSession();
}
}
控制台顯示:
Hibernate:
insert
into
PERSON
(NAME, AGE, GENDER, ADDRESS)
values
(?, ?, ?, ?)
Hibernate:
delete
from
PERSON
where
ID=?
Hibernate:
insert
into
PERSON
(NAME, AGE, GENDER, ADDRESS)
values
(?, ?, ?, ?)
按照Hibernate的規定執行應該是insert,insert,delete,但不知道為什麼這裡是insert,delete,insert,請各位大哥指教一下。
數據庫執行sql時,遵循事務原則。按照你的程序執行順序就應該是save(insert)、delete、save(insert)呀。還有你的ID難道不是唯一的嗎?為什麼能設置為空很難理解。