0
我試圖更新數據庫中的記錄,並在提交記錄之前,我想查看記錄是否更新。不幸的是,它沒有顯示更新的結果。query.executeUpdate()休眠後,它不是在提交之前查詢時更新的值
public class MainApp {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
SessionFactory sessionFactory =HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Employee emp;
Transaction tx = session.beginTransaction();
// Get Employee with id
Query query = session.createQuery("from Employee where id= :id");
query.setLong("id", 3);
emp = (Employee) query.uniqueResult();
System.out.println("Employee ID : " + emp.getId() + " Employee name : " + emp.getName() + " ; Employee Salary : " + emp.getSalary() + " ; Employee City : " + emp.getAddress().getCity());
// Update Employee
query = session.createQuery("update Employee set name= :name where id= :id");
query.setParameter("name", "xyz");
query.setLong("id", 3);
int result = query.executeUpdate();
System.out.println("Employee Update Status=" + result);
// Get Employee with id
query = session.createQuery("from Employee where id= :id");
query.setLong("id", 3);
emp = (Employee) query.uniqueResult();
System.out.println("Employee Name=" + emp.getName() + ", City=" + emp.getAddress().getCity());
// closing hibernate resources
tx.commit();
session.close();
sessionFactory.close();
System.out.println("Success...");
}
}
在上面的代碼首先我詢問與員工ID 3的員工,然後更新從「ABC」該員工的姓名爲「XYZ」,然後查詢一個員工看到它的名字是否已經被是否更新。我仍然得到舊的名稱是「abc」。
如果hibernate首先在緩存中本地更新對象,並最終在提交事務時將其更新到數據庫中,那麼在第二次查詢同一對象時,應返回包含更新值的本地緩存中的同一對象。但事實並非如此。
感謝@JB Nizet的解釋... !!! – kverma28