Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在query.executeUpdate()hibernate之后,它不是提交之前查询时的更新值_Hibernate - Fatal编程技术网

在query.executeUpdate()hibernate之后,它不是提交之前查询时的更新值

在query.executeUpdate()hibernate之后,它不是提交之前查询时的更新值,hibernate,Hibernate,我正在尝试更新数据库中的一条记录,在提交该记录之前,我想查看该记录是否已更新。不幸的是,它没有显示更新的结果 public class MainApp { @SuppressWarnings("unchecked") public static void main(String[] args) { SessionFactory sessionFactory =HibernateUtil.getSessionFactory(); Session s

我正在尝试更新数据库中的一条记录,在提交该记录之前,我想查看该记录是否已更新。不幸的是,它没有显示更新的结果

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首先在缓存中本地更新对象,然后在提交事务时将其更新为db,那么在第二次查询同一对象时,应该从本地缓存返回包含更新值的同一对象。但事实并非如此。

这是意料之中的。更新查询不影响内存中的状态。由于您在执行更新查询之前已在会话中加载员工,因此其状态不受影响

您需要清除会话,或者停止使用更新查询:只需使用

emp.setName("xyz");
这就是更改员工姓名所需的全部内容

还要注意的是,select查询也是无用的。您应该只使用
session.get()