我使用Spring with Hibernate进行事务管理。对于SessionFactory,我有一个自定义实现类HRSessionFactory,如下所示:
package com.practice.swh.entity;
import java.io.Serializable;
import java.sql.Connection;
import java.util.Map;
import java.util.Set;
import javax.naming.NamingException;
import javax.naming.Reference;
import org.hibernate.Cache;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.StatelessSessionBuilder;
import org.hibernate.TypeHelper;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.stat.Statistics;
public class HRSessionFactory implements SessionFactory {
private SessionFactory sessionFactory;
@Override
public void close() throws HibernateException {
sessionFactory.close();
}
@Override
public void evict(Class arg0, Serializable arg1) throws HibernateException {
sessionFactory.evict(arg0, arg1);
}
@Override
public void evict(Class arg0) throws HibernateException {
sessionFactory.evict(arg0);
}
@Override
public void evictCollection(String arg0, Serializable arg1) throws HibernateException {
sessionFactory.evictCollection(arg0, arg1);
}
@Override
public void evictCollection(String arg0) throws HibernateException {
sessionFactory.evictCollection(arg0);
}
@Override
public void evictEntity(String arg0, Serializable arg1) throws HibernateException {
sessionFactory.evictEntity(arg0, arg1);
}
@Override
public void evictEntity(String arg0) throws HibernateException {
sessionFactory.evictEntity(arg0);
}
@Override
public void evictQueries() throws HibernateException {
sessionFactory.evictQueries();
}
@Override
public void evictQueries(String arg0) throws HibernateException {
sessionFactory.evictQueries(arg0);
}
@Override
public Map getAllClassMetadata() throws HibernateException {
return sessionFactory.getAllClassMetadata();
}
@Override
public Map getAllCollectionMetadata() throws HibernateException {
return sessionFactory.getAllCollectionMetadata();
}
@Override
public ClassMetadata getClassMetadata(Class arg0) throws HibernateException {
return sessionFactory.getClassMetadata(arg0);
}
@Override
public ClassMetadata getClassMetadata(String arg0) throws HibernateException {
return sessionFactory.getClassMetadata(arg0);
}
@Override
public CollectionMetadata getCollectionMetadata(String arg0) throws HibernateException {
return sessionFactory.getCollectionMetadata(arg0);
}
@Override
public Session getCurrentSession() throws HibernateException {
return sessionFactory.getCurrentSession();
}
@Override
public Set getDefinedFilterNames() {
return sessionFactory.getDefinedFilterNames();
}
@Override
public FilterDefinition getFilterDefinition(String arg0) throws HibernateException {
return sessionFactory.getFilterDefinition(arg0);
}
@Override
public Statistics getStatistics() {
return sessionFactory.getStatistics();
}
@Override
public boolean isClosed() {
return sessionFactory.isClosed();
}
@Override
public Session openSession() throws HibernateException {
return sessionFactory.openSession();
}
@Override
public StatelessSession openStatelessSession() {
return sessionFactory.openStatelessSession();
}
@Override
public StatelessSession openStatelessSession(Connection arg0) {
return sessionFactory.openStatelessSession(arg0);
}
@Override
public Reference getReference() throws NamingException {
return sessionFactory.getReference();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Override
public String toString() {
return String.valueOf(sessionFactory.hashCode());
}
@Override
public boolean containsFetchProfileDefinition(String arg0) {
return sessionFactory.containsFetchProfileDefinition(arg0);
}
@Override
public Cache getCache() {
return sessionFactory.getCache();
}
@Override
public SessionFactoryOptions getSessionFactoryOptions() {
return sessionFactory.getSessionFactoryOptions();
}
@Override
public TypeHelper getTypeHelper() {
return sessionFactory.getTypeHelper();
}
@Override
public SessionBuilder withOptions() {
return sessionFactory.withOptions();
}
@Override
public StatelessSessionBuilder withStatelessOptions() {
return sessionFactory.withStatelessOptions();
}
}
我的申请背景如下:
<?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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/disautomation"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="com.practice.swh.entity.HRSessionFactory">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="executeQuery*" propagation="REQUIRES_NEW" rollback-for="Exception"/>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.practice.swh.manager..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
</aop:config>
<bean id="employeeDao" class="com.practice.swh.dao.impl.EmployeeDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="employeeManager" class="com.practice.swh.manager.impl.EmployeeManagerImpl">
<property name="employeeDao" ref="employeeDao"></property>
<property name="dummyManager" ref="dummyManager"></property>
</bean>
</beans>
经理实施:
package com.practice.swh.manager.impl;
import com.practice.swh.dao.EmployeeDao;
import com.practice.swh.entity.Employee;
import com.practice.swh.manager.EmployeeManager;
public class EmployeeManagerImpl implements EmployeeManager {
private EmployeeDao employeeDao;
@Override
public Employee getEmployee(Integer employeeId) {
Employee employee = employeeDao.getEmployee(employeeId);
//System.out.println(employee.getDepartment());
//System.out.println(employee.getAddresses());
return employee;
}
public EmployeeDao getEmployeeDao() {
return employeeDao;
}
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
}
道实施:
package com.practice.swh.dao.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.practice.swh.dao.EmployeeDao;
import com.practice.swh.entity.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
@Override
public Employee getEmployee(Integer employeeId) {
Session session = sessionFactory.getCurrentSession();
return (Employee) session.get(Employee.class, employeeId);
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
我的测试班:
package com.practice.swh.client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.practice.swh.entity.Employee;
import com.practice.swh.manager.EmployeeManager;
public class EmployeeTest {
public static void main(String[] args) {
getEmployeeTest();
}
private static void getEmployeeTest() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeManager employeeManager = (EmployeeManager) ctx.getBean("employeeManager");
Employee employee = employeeManager.getEmployee(4);
System.out.println(employee);
}
}
当我执行测试类时,我得到以下异常:
Exception in thread "main" org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:883)
at com.practice.swh.entity.HRSessionFactory.getCurrentSession(HRSessionFactory.java:100)
at com.practice.swh.dao.impl.EmployeeDaoImpl.getEmployee(EmployeeDaoImpl.java:34)
at com.practice.swh.manager.impl.EmployeeManagerImpl.getEmployee(EmployeeManagerImpl.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy6.getEmployee(Unknown Source)
at com.practice.swh.client.EmployeeTest.getEmployeeTest(EmployeeTest.java:35)
at com.practice.swh.client.EmployeeTest.main(EmployeeTest.java:12)
但是,当我将应用程序上下文更改为不使用自定义会话工厂时,代码可以正常工作:
<?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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/disautomation"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- <bean id="sessionFactory" class="com.practice.swh.entity.HRSessionFactory">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean> -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
<value>department.hbm.xml</value>
<value>employeeAddress.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="executeQuery*" propagation="REQUIRES_NEW" rollback-for="Exception"/>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.practice.swh.manager..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
</aop:config>
<bean id="employeeDao" class="com.practice.swh.dao.impl.EmployeeDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="employeeManager" class="com.practice.swh.manager.impl.EmployeeManagerImpl">
<property name="employeeDao" ref="employeeDao"></property>
<property name="dummyManager" ref="dummyManager"></property>
</bean>
</beans>
如果我使用自定义SessionFactory实现会出现什么问题?
答案 0 :(得分:0)
您的代码中存在两个问题:
第一。注入Spring bean时必须使用@Autowire
注释才能正确使用它们。
第二。当您使用事务管理器sessionFactory
时,您应该使用@Transaction
注释来注释服务或dao方法
试一试,看看是否有帮助