Spring Hibernate集成抛出getFlushMode在没有活动事务的情况下无效



我正在按照教程处理一个示例 Spring Hibernate 示例,并遇到了异常说

 Exception in thread "main"
 org.springframework.orm.hibernate4.HibernateSystemException: getFlushMode 
 is not valid without active transaction; nested exception is 
 org.hibernate.HibernateException: getFlushMode is not valid without active
 transaction

这是我的代码:

人.java - 简单的POJO

public class Person {
    private Integer id;
    private String name;
    private String email;
    // Setters & Getters
}

person.hbm.xml - 映射文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.examples.model.Person"
        table="PERSON">
        <id column="ID" name="id">
            <generator class="increment" />
        </id>
        <property name="name" column="NAME" />
        <property name="email" column="EMAIL" />
    </class>
</hibernate-mapping>

人道.java - 我的道类

import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import com.examples.model.Person;
public class PersonDao extends HibernateDaoSupport {
    public void insert(Person person) {
        getHibernateTemplate().save(person);
    }
    public List selectAll() {
        DetachedCriteria criteria = DetachedCriteria.forClass(Person.class);
        return getHibernateTemplate().findByCriteria(criteria);
    }
}

人员服务.java - 服务层

public class PersonService {
    private PersonDao personDao;
    public PersonDao getPersonDao() {
        return personDao;
    }
    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }
    public void addPerson(Person person) {
        getPersonDao().insert(person);
    }
    public List<Person> fetchAllPersons() {
        return getPersonDao().selectAll();
    }
}

spring-config.xml - spring 配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <bean id="personService"
        class="com.examples.service.PersonService">
        <property name="personDao" ref="personDao" />
    </bean>
    <bean id="personDao"
        class="com.examples.dao.PersonDao">
        <property name="hibernateTemplate" ref="hibernateTemplate" />
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>com/examples/model/person.hbm.xml
                </value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
            </props>
        </property>
    </bean>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/hib" />
        <property name="username" value="root" />
        <property name="password" value="admin" />
    </bean>
</beans>

最后是我的主要程序 - MainApp.java

public class MainApp {
    public static void main(String[] args) {
        System.out.println("************** BEGINNING PROGRAM **************");
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring-config.xml");
        PersonService personService = (PersonService) context
                .getBean("personService");
        Person person = new Person();
        person.setName("Robin");
        person.setEmail("robin@gmail.com");
        personService.addPerson(person);
        System.out.println("Person : " + person + " added successfully");
        List<Person> persons = personService.fetchAllPersons();
        System.out.println("The list of all persons = " + persons);
        System.out.println("************** ENDING PROGRAM *****************");
    }
}

当我运行该程序时,我得到以下异常:

Exception in thread "main" org.springframework.orm.hibernate4.HibernateSystemException: getFlushMode is not valid without active transaction; nested exception is org.hibernate.HibernateException: getFlushMode is not valid without active transaction
    at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:216)
    at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:343)
    at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
    at org.springframework.orm.hibernate4.HibernateTemplate.save(HibernateTemplate.java:617)
    at com.examples.dao.PersonDao.insert(PersonDao.java:13)
    at com.examples.service.PersonService.addPerson(PersonService.java:21)
    at com.examples.MainApp.main(MainApp.java:24)
Caused by: org.hibernate.HibernateException: getFlushMode is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
    at com.sun.proxy.$Proxy6.getFlushMode(Unknown Source)
    at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1134)
    at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:620)
    at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:617)
    at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
    ... 5 more

我遵循了这篇SO帖子中给出的解决方案 - 春季/休眠异常:如果没有活动事务,createCriteria无效

然后我得到了一个例外说:

Exception in thread "main" 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.

请帮我如何解决这个问题?

正如错误所说,你必须使用事务,所以在你的 spring 配置文件中声明事务管理器:

<bean id="txManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="get*" read-only="true" />
        <tx:method name="*" />
    </tx:attributes>
</tx:advice>
<aop:config>
    <aop:pointcut id="personServiceOperation"
        expression="execution(* com.examples.service.PersonService.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="personServiceOperation" />
</aop:config>

这里我们还需要使用 aoptx 命名空间,因此更新 beans 的命名空间声明如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">  

最后删除配置文件中的以下行:

<prop key="hibernate.current_session_context_class">thread</prop>

最新更新