为什么我不能在休眠状态下改变 flushmode

Why i can not change flushmode in hibernate

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

我试图在代码和 xml 中将其更改为另一个 flushmode 但它仍然是自动的。

hibernatetemplate.getSessionFactory().openSession().setFlushMode(FlushMode.COMMIT);

<prop key="org.hibernate.FlushMode">COMMIT</prop>

很可能您的操作(其中一些是持久化或更新实体)在会话中不在事务上下文中。

尝试将它们包含在:

Session session = hibernatetemplate.getSessionFactory().openSession();
Transaction tx = session.beginTrasaction();

...

tx.commit();
session.close();

现在,当您开始事务时,刷新模式应该隐式设置为 COMMIT/AUTO。

其实我解决了

final Person object = new Person(id, name, password);
    hibernateTemplate.execute(new HibernateCallback<Person>() {

        public Person doInHibernate(Session session)
                throws HibernateException {

            session.save(object);
            session.flush();
            return object;
        }
    });

你可以创建 hibernateTemplate 对象并覆盖 excute 方法