#java #hibernate #spring
#java #спящий режим #весна
Вопрос:
Я искал на форуме этот ответ, но не смог найти решение. Я настроил свой компонент управления транзакциями
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Я настроил свою фабрику сеансов.
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/hibernate"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>org.krams.tutorial.domain.Person</value>
<value>org.krams.tutorial.domain.UserRole</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
В моем классе DaoImpl и Service есть тег @repository и @transactional
@Repository("personDao")
public class PersonDAOImpl implements PersonDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public void savePerson(Person person) {
sessionFactory.getCurrentSession().saveOrUpdate (person);
}
@Override
public Person findByName(String name){
String query = "select * from Person p where p.username='" name "'";
Person person = (Person) sessionFactory.getCurrentSession().createQuery(query);
return person;
}
}
@Service("userService")
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class PersonServiceImpl implements PersonService{
@Autowired
private PersonDAO personDao;
@Override
@Transactional(propagation=Propagation.SUPPORTS, readOnly=false)
public void savePerson(Person person) {
personDao.savePerson(person);
}
@Override
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public Person findByName(String name){
return personDao.findByName(name);
}
}
У меня есть еще один класс обслуживания для реализации базы данных Spring Security
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private PersonService userService;
@Autowired
private Assembler assembler;
@Transactional(readOnly = true)
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
try {
Person person = userService.findByName(username);
return (UserDetails) assembler.buildUserFromUserEntity(person);
} catch (NoResultException e) {
throw new UsernameNotFoundException(e.getLocalizedMessage());
}
}
}
отслеживание стека:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544)
at org.krams.tutorial.dao.PersonDAOImpl.findByName(PersonDAOImpl.java:30)
at org.krams.tutorial.service.PersonServiceImpl.findByName(PersonServiceImpl.java:40)
at org.krams.tutorial.service.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:37)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:82)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:124)
at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:120)
at org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:48)
at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:138)
at org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:48)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:97)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Я в замешательстве, так как где я ошибся. Пожалуйста, ребята, помогите мне.
Комментарии:
1. пожалуйста, отправьте трассировку стека ошибки
2. HefferWolf: я обновил свой вопрос. Вы можете найти прикрепленную трассировку стека
Ответ №1:
Похоже, вы пропустили включение поддержки транзакций.
Добавить tx:annotation-driven
в конфигурацию:
<beans
...
xmlns:tx="http://www.springframework.org/schema/tx"
...
xsi:schemaLocation="...
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
...
<tx:annotation-driven transaction-manager="transactionManager" />