java - HibernateexecuteUpdate成功但列表操作未反射(reflect)更改

标签 java mysql hibernate

我正在遵循 Internet 上的简单 Hibernate 教程。看起来executeUpdate 成功了(返回的行数为1)。但是,当我调用 list() 时,它返回了旧结果。这是 hibernate 的预期行为吗?无论如何,我可以在同一笔交易中获取更新的数据吗?

这是我的源代码:

//Prep work
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.getCurrentSession();

    //Get All Employees
    Transaction tx = session.beginTransaction();
    Query query = session.createQuery("from Employee");
    List<Employee> empList = query.list();
    for(Employee emp : empList){
        System.out.println("List of Employees::"+emp.getId()+","+emp.getAddress().getCity());
    }
    //Update Employee
    query = session.createQuery("update Employee set name= :name where id= :id");
    query.setParameter("name", "Pankaj Kumar");
    query.setLong("id", 1);
    int result = query.executeUpdate();
    System.out.println("Employee Update Status="+result);


    query = session.createQuery("from Employee");
    empList = query.list();
    for(Employee emp : empList){
        System.out.println("List of Employees::"+emp.getId()+","+emp.getAddress().getCity());
    }

    //rolling back to save the test data
    tx.rollback();

    //closing hibernate resources
    sessionFactory.close();

返回结果:

List of Employees::1,San Jose
List of Employees::2,Santa Clara
List of Employees::3,Bangalore
List of Employees::4,New Delhi
Hibernate: update EMPLOYEE set emp_name=? where emp_id=?
Employee Update Status=1
Hibernate: select employee0_.emp_id as emp_id1_1_, employee0_.emp_name as emp_name2_1_, employee0_.emp_salary as emp_sala3_1_ from EMPLOYEE employee0_
List of Employees::1,San Jose
List of Employees::2,Santa Clara
List of Employees::3,Bangalore
List of Employees::4,New Delhi

最佳答案

事务提交后,更改实际上会保存到数据库,这就是事务的全部意义。

如果您面临需要更新数据库上的数据的情况,那么将其获取以进行进一步处理,或者在将驻留在持久性上下文中的对象上本地更新它(在这种情况下将更有意义) createOrUpdate 而不是您的查询),或者将这两个步骤分成 2 个事务

关于java - HibernateexecuteUpdate成功但列表操作未反射(reflect)更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44019432/

相关文章:

java - Dropwizard Forms MULTIPART - 启动时资源抛出错误

java - 何时以及为何使用 EclipseLink 缓存?

java - 在 if boolean 表达式中递增 int

mysql - Magento+ 添加到购物车不起作用

php - 每个月自动递增从 1 在 mysql 中用 php 开始

java - 带有大表的 setMaxResults 使用太多内存

java - Project Euler 14(Collat​​z 猜想),Java 中实现缓存的问题

php - 从 mysql 转换为 PDO 用户名确认问题

java - Hibernate + SQLite 使用 hibernate.hbm2ddl.auto = auto 更新表

java - Hibernate:如何从 Hibernate 测试套件开始单个测试?