我在Spring3和Hibernte4中遇到上述异常
以下是我的bean xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> <context:annotation-config/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/GHS"/> <property name="username" value="root"/> <property name="password" value="newpwd"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.example.ghs.model.timetable</value> </list> </property> </bean> <bean id="baseDAO" class="com.example.ghs.dao.BaseDAOImpl"/> </beans>
我的BaseDAO类看起来像这样
public class BaseDAOImpl implements BaseDAO{ private SessionFactory sessionFactory; @Autowired public BaseDAOImpl(SessionFactory sessionFactory){ this.sessionFactory = sessionFactory; } @Override public Session getCurrentSession(){ return sessionFactory.getCurrentSession(); } }
以下代码在标题中引发异常
public class Main { public static void main(String[] args){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dao-beans.xml"); BaseDAO bd = (BaseDAO) context.getBean("baseDAO"); bd.getCurrentSession(); } }
有谁知道如何解决这个问题?
getCurrentSession() 仅在交易范围内有意义。
getCurrentSession()
你需要声明一个合适的事务管理器,划分事务边界并在其中进行数据访问。例如,如下:
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean>
。
PlatformTransactionManager ptm = context.getBean(PlatformTransactionManager.class); TransactionTemplate tx = new TransactionTemplate(ptm); tx.execute(new TransactionCallbackWithoutResult() { public void doInTransactionWithoutResult(TransactionStatus status) { // Perform data access here } });