Я пытаюсь использовать делегированные транзакции Hibernate с использованием Spring в приложении демо автономной, используя DAO слой и слой Service.Нет сеанса найдено для текущего потока, Spring 3.1 и Hibernate 4
Я правильно установить конфигурацию, и я блок-тестирование, что использования @Transactional аннотацию о методах DAO работает отлично, но когда я переместить эту аннотацию службы слой в я получаю:
org.hibernate.HibernateException: No Session found for current thread
Я обеспечиваю наиболее соответствующие части моего кода, надеясь, что вы можете бросить мне намек, чтобы понять, что здесь происходит.
applicationContext.xml
<beans ...>
<context:component-scan base-package="com.genericdao" />
<!-- delegat transactions -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- sessionFactory config -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:com/genericdao/hbm</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SybaseAnywhereDialect</prop>
<!--prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop--><!-- i tried commenting this line -->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop><!-- i know this is provided by default -->
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
... i provide here configuration
</bean>
</beans>
ДАО слой
getSession() просто выполняет sessionFactory.getCurrentSession(); и SessionFactory является autowired в GenericDaoHibernateImpl
@Repository("userLoginDao")
public class UserLoginDaoImpl extends GenericDaoHibernateImpl<UserLogin, Integer> implements UserLoginDao{
@Override
//@Transactional(readOnly=true) // This works when i unit-test!! But I don't want to use @Transactional here!!
public List<UserLogin> findAll() {
boolean active = TransactionSynchronizationManager.isActualTransactionActive(); // always true if i use @Transactional
Query query = getSession().createQuery("from UserLogin");
return (List<UserLogin>) query.list();
}
}
Service Layer
@Service("pruebaService")
public class PruebaServiceImpl implements PruebaService{
private static final ApplicationContext ctx;
static{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
/**********************************************************
* HERE i want to use @Transactional, but it doesn't work because
* i get the org.hibernate.HibernateException: No Session found for current thread
* when i test invocation of this method...
* NOTE: I want to state, that if i uncomment the Dao @Transactional line
* then this works!!, but as i mentioned before i really don't want to have transactions on DAO methods, just Service Methods!!
*/
@Override
@Transactional(readOnly=true)
public List<UserLogin> obtenerTodasLasCuentas() {
UserLoginDao bean = (UserLoginDao) ctx.getBean("userLoginDao");
List<UserLogin> result = bean.findAll();
return result;
}
}
Я действительно сделал Серч на эту тему, но я не мог найти правильный вход ... надежда вы можете помочь с этим ... спасибо.
обновление:
Вот тестирование соответствующий код я использую
тестирования кода
@Test
public void selectTest(){
pruebaService = (PruebaService) ctx.getBean("pruebaService");
Assert.assertNotNull(pruebaService); // This assert is good, so i know service is properly injected
List<UserLogin> result = pruebaService.obtenerTodasLasCuentas();
Assert.assertNotNull(result); // This line is never reached because of the exception i mentioned!!
}
Какой пакет входит в класс обслуживания? –
@SotiriosDelimanolis, вероятно, на правильном пути. Если Spring не создает ваш класс PruebaServiceImpl, он не увидит аннотацию '@ Transactional' и не сможет создать необходимый аспект. – Pace
@SotiriosDelimanolis @Pace Service находится на 'com.genericdao.service', поэтому на самом деле он создан, и он видит' @ Transactional', потому что когда я тестирую 'TransactionSynchronizationManager.isActualTransactionActive() '(метод DAO findAll), он всегда оценивается как истинный –