WebアプリケーションでSpring3.1+Hibernate4.xを使用しています。私のDAOでは、ユーザータイプオブジェクトを次のように保存しています
sessionFactory.getCurrentSession().save(user);
ただし、次の例外が発生します。
org.hibernate.HibernateException: save is not valid without active transaction
私はグーグルで検索し、SOで同様の質問を見つけました。次の解決策があります。
Session session=getSessionFactory().getCurrentSession();
Transaction trans=session.beginTransaction();
session.save(entity);
trans.commit();
それで問題は解決します。しかし、そのソリューションでは、トランザクションを手動で開始してコミットするという混乱がたくさんあります。
sessionFactory.getCurrentSession().save(user);
トランザクションの開始/コミットなしで直接使用することはできません か?
@Transactional
service / daoメソッドでも使用しようとしていますが、問題は解決しません。
編集:これが私の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:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${db.driverClassName}" p:url="${db.url}"
p:username="${db.username}" p:password="${db.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.myapp.entities" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
私は次のHibernate4依存関係を使用しています:
<!-- Hibernate Dependency -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.1.Final</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
<scope>runtime</scope>
</dependency>
助けてください。