如果没有活动事务,Spring Hibernate集成抛出getFlushMode无效 [英] Spring Hibernate integration throws getFlushMode is not valid without active transaction

查看:67
本文介绍了如果没有活动事务,Spring Hibernate集成抛出getFlushMode无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习一个Spring Hibernate示例的示例,它遵循一个教程,并且遇到了一个例外情况:

 线程中的异常main
org.springframework.orm.hibernate4.HibernateSystemException:getFlushMode
没有活动事务无效;嵌套异常是
org.hibernate.HibernateException:如果没有活动
事务



,getFlushMode无效

这是我的代码:
$ b Person.java - 简单的POJO

  public class Person {
private Integer id;
私人字符串名称;
私人字符串电子邮件;
// Setters&获取者
}

person.hbm.xml - 映射文件

 <?xml version =1.0?> 
<!DOCTYPE hibernate-mapping PUBLIC
- // Hibernate / Hibernate映射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 =IDname =id>
< generator class =increment/>
< / id>
< property name =namecolumn =NAME/>
< property name =emailcolumn =EMAIL/>
< / class>
< / hibernate-mapping>

PersonDao.java - 我的DAO类

  import java.util.List; 

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.examples.model.Person;
$ b public class PersonDao extends HibernateDaoSupport {
$ b $ public void insert(Person person){
getHibernateTemplate()。save(person);
}

public List selectAll(){
DetachedCriteria criteria = DetachedCriteria.forClass(Person.class);
return getHibernateTemplate()。findByCriteria(criteria);
}

}

PersonService.java - 服务层

  public class PersonService {
$ b $ private 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.0encoding =UTF-8?> 
< beans xmlns =http://www.springframework.org/schema/beans
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns :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/上下文
http://www.springframework.org/schema/context/spring-context-3.0.xsd\">

< bean id =personService
class =com.examples.service.PersonService>
< property name =personDaoref =personDao/>
< / bean>

< bean id =personDao
class =com.examples.dao.PersonDao>
< property name =hibernateTemplateref =hibernateTemplate/>
< / bean>

< bean id =hibernateTemplateclass =org.springframework.orm.hibernate4.HibernateTemplate>
< property name =sessionFactoryref =sessionFactory/>
< / bean>

< bean id =sessionFactory
class =org.springframework.orm.hibernate4.LocalSessionFactoryBean>
< property name =dataSourceref =dataSource/>
< property name =mappingResources>
< list>
< value> com / examples / model / person.hbm.xml
< / value>
< / list>
< / property>
< property name =hibernateProperties>
<道具>
< prop key =hibernate.dialect> org.hibernate.dialect.MySQLDialect< / prop>
< prop key =hibernate.current_session_context_class> thread< / prop>
< /道具>
< / property>

< / bean>

< bean id =dataSource
class =org.springframework.jdbc.datasource.DriverManagerDataSource>
< property name =driverClassNamevalue =com.mysql.jdbc.Driver/>
< property name =urlvalue =jdbc:mysql://127.0.0.1:3306 / hib/>
< property name =usernamevalue =root/>
< property name =passwordvalue =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);

列表< Person> persons = personService.fetchAllPersons();
System.out.println(所有人员列表=+人员);

System.out.println(************** ENDING PROGRAM *****************) ;


$ / code>

当我运行程序时,出现异常:

 线程main中的异常org.springframework.orm.hibernate4.HibernateSystemException:如果没有活动事务,getFlushMode无效;嵌套的例外是org.hibernate.HibernateException:getFlushMode也不是没有在org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:216)
活动事务
在org.springframework.orm有效。 hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:343)
处org.springframework.orm.hibernate4.HibernateTemplate org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
。保存(HibernateTemplate.java:617)
在com.examples.dao.PersonDao.insert(PersonDao.java:13)
在com.examples.service.PersonService.addPerson(PersonService.java:21)在com.examples.MainApp.main
(MainApp.java:24)
引起的:org.hibernate.HibernateException:getFlushMode也不是没有在org.hibernate.context活跃交易
有效。 internal.ThreadLocalSessionContext $ TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
。在com.sun.proxy。$ Proxy6.getFlushMode(来源不明)处org.springframework org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1134)

。 orm.hibernate4.HibernateTemplate $ 12.doInHibernate(HibernateTemplate.java:620)维持在org.springframework.orm org.springframework.orm.hibernate4.HibernateTemplate $ 12.doInHibernate(HibernateTemplate.java:617)

。 hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
... 5 more

我遵循这个SO帖子中给出的解决方案 - Spring / Hibernate异常:createCriteria在没有活动事务的情况下无效



然后我得到一个异常:

 线程main中的异常org.springframework.dao.InvalidDataAccessApiUsageException:写入o perations不允许在只读模式下使用(FlushMode.MANUAL):将会话变为FlushMode.COMMIT / AUTO或从事务定义中移除'readOnly'标记。 

请帮助我解决这个问题?

解决方案

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

 < bean id =txManager
class =org.springframework.orm.hibernate4.HibernateTransactionManager>
< property name =sessionFactoryref =sessionFactory/>
< / bean>

< tx:advice id =txAdvicetransaction-manager =txManager>
< tx:attributes>
< tx:方法名称=get *只读=true/>
< tx:method name =*/>
< / tx:属性>
< / tx:advice>

< aop:config>
< aop:pointcut id =personServiceOperation
expression =execution(* com.examples.service.PersonService。*(..))/>
< / aop:config>

这里我们还需要使用 aop tx 命名空间,因此请更新 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> 


I am working on a sample Spring Hibernate example by following a tutorial and got stuck with the exception saying

 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

Here is my code:

Person.java - Simple POJO

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

person.hbm.xml - Mapping file

<?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>

PersonDao.java - My DAO Class

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);
    }

}

PersonService.java - Service layer

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 Configuration file:

<?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>

Finally my main program - 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 *****************");
    }
}

When I run the program I am getting below exception:

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

I followed the solution given in this SO post - Spring/Hibernate Exception: createCriteria is not valid without active transaction

then I got an exception saying:

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.

Please help me how to fix this issue?

解决方案

As the error says, you have to use transactions, so declare transaction manager in your spring configuration file :

<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>

Here we also need to use the aop and tx namespace, so update the namespace declaration for beans as follows:

<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">  

Finally delete the below line in your configuration file:

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

这篇关于如果没有活动事务,Spring Hibernate集成抛出getFlushMode无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆