我得到以下错误
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:1024)
at com.fexco.shoptaxfreemobile.service.ProfileService.registerVisitor(ProfileService.java:57)
at com.fexco.shoptaxfreemobile.controller.ProfileController.registerVisitor(ProfileController.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.fexco.shoptaxfreemobile.jsonp.JsonpCallbackFilter.doFilter(JsonpCallbackFilter.java:33)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
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:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
服务类
@Service
public class ProfileService {
@Resource(name = "mySessionFactory")
private SessionFactory sessionFactory;
@Autowired
private ProfileDao profileDao;
private class CountrySorter implements Comparator<Country> {
@Override
public int compare(Country country1, Country country2) {
if ( country1.getId().compareTo(new Long (3)) < 0){
return country1.getId().compareTo(country2.getId());
}
return country1.getName().compareToIgnoreCase(country2.getName());
}
}
public List<Country> getCountries() {
List<VisitorCountry> visitorCountries = profileDao.getAllCountries();
List<Country> countries = new ArrayList<Country>();
for ( VisitorCountry country : visitorCountries){
countries.add(country.getCountry());
}
Comparator<Country> comparator = new CountrySorter();
Collections.sort(countries, comparator);
return countries;
}
public RegisterResponse registerVisitor(JsonVisitor visitorDetails){
Visitor storedVisitor = (Visitor) sessionFactory.getCurrentSession().get(Visitor.class, visitorDetails.getTfscNumber(), LockMode.NONE);
if ( storedVisitor == null){
storedVisitor = new Visitor(visitorDetails);
}else{
storedVisitor.setVisitorDetails(visitorDetails);
}
try{
sessionFactory.getCurrentSession().saveOrUpdate(storedVisitor);
}catch(Exception ex){
return new RegisterResponse(false, "Failed To Register Card. Please Try Again Later.", visitorDetails);
}
return new RegisterResponse(true, "", visitorDetails);
}
}
DAO课程
@Service
@Transactional
public class ProfileDao {
@Resource(name = "mySessionFactory")
private SessionFactory sessionFactory;
public List getAllCountries(){
List<VisitorCountry> visitorCountries = sessionFactory.getCurrentSession()
.getNamedQuery("GET_ALL_COUNTRIES").list();
return visitorCountries;
}
public List<Retailer> getRetailerByRetailerNumber(String retailerNo) {
List<Retailer> retailerByRetailerNumber = sessionFactory.getCurrentSession()
.getNamedQuery("FindRetailerByRetailerNo").setString("retailerNo", retailerNo).list();
return retailerByRetailerNumber;
}
我在application-context.xml
中有这个<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties">
<value>
<![CDATA[
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider
]]>
</value>
</property>
</bean>
有人能发现我为什么会收到以下错误吗?
答案 0 :(得分:44)
您使用@Transactional注释了您的Dao类,但没有注释您的服务类。这一行:
Visitor storedVisitor =
(Visitor) sessionFactory.getCurrentSession().get(Visitor.class,
visitorDetails.getTfscNumber(), LockMode.NONE);
要求您参与交易。
您可以通过将@Transactional注释添加到ProfileService类或仅注册registerVisitor()方法来解决此问题。
答案 1 :(得分:11)
我通过以下两个步骤解决了同样的问题
按照建议在服务方法上放置@Transactional
jordan002 在他的回答中。
还有一件事,如果您有2个配置文件:比如说
application-context.xml
(适用于数据库和应用程序上下文特定
配置)和webmvc-context.xml
(适用于特定于Web /控制器
配置),那么你应该扫描不同的包
控制器和道。
在webmvc-context.xml
之后加载application-context.xml
。
我认为首先使用事务引用加载DAO类
加载application-context.xml时,但是替换为
另一个没有事务引用的对象,何时
webmvc-context.xml已加载。
无论如何,我使用扫描的特定包解决了问题:
<context:component-scan base-package="com.app.repository" />
代表application-context.xml
和
<context:component-scan base-package="com.app.web" />
代表webmvc-context.xml
。
答案 2 :(得分:5)
使用@Repository
更改DAO的注释@Repository
public class ProfileDao {
.
.
.
}
然后将您的服务方法@Transactional设为例如
@Transactional
public List<Retailer> getRetailerByRetailerNumber(String retailerNo) {}
答案 3 :(得分:3)
我通过以下两步解决了上述问题
1 - 在我调用DAO方法的服务方法中添加@Transactional支持
2 - 以这种方式在spring-servlet.xml中导入applicationContext.xml
<import resource="applicationContext.xml" />
<mvc:annotation-driven />
<context:component-scan base-package="com.json.api.*" />
<!--Third Party Integration should be injected in xml start here -->
<bean id="integrationInterface" class="com.json.api.IntegerationInterface"></bean>
<!--Third Party Integration should be injected in xml start here -->
<mvc:interceptors>
<bean id="apiServiceInterceptor" class="com.json.api.interceptor.ApiServiceInterceptor"></bean>
</mvc:interceptors>
<!--To Enable @Value to map key with provided fields for property files -->
<context:property-placeholder />
它消除了在两个地方spring-servlet.xml和applicationContext.xml
扫描包的需要答案 4 :(得分:1)
我知道这是一个有一定年龄的问题,但我遇到了这个问题并发现如果你使用的是Spring-Java配置,那么解决方案有两个部分。某些配置相对于控制器的相对位置很重要。
首先,CoreConfiguration
@Configuration
public class CoreConfiguration {
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factoryBean = new org.springframework.orm.hibernate4.LocalSessionFactoryBean();
String annotatedPckgs[] ={"org.tigersndragons.reports.model.warehouse"};
factoryBean.setAnnotatedPackages(annotatedPckgs);
Properties hibernateProperties = new Properties();
try {
hibernateProperties.load(this.getClass().getResourceAsStream("props/hibernate.properties"));
factoryBean.setHibernateProperties(hibernateProperties);
} catch (IOException e) { }
factoryBean.setPackagesToScan("org.telligen.reports.model.warehouse");
factoryBean.setDataSource(warehouseDataSource());//("jdbc/warehouse");
try {
factoryBean.afterPropertiesSet();
} catch (IOException e) { }
return factoryBean;
}
@Bean
public WarehouseDAO getWarehouseDAO(){
WarehouseDAO wrhsDao = new WarehouseDAO();
wrhsDao.setSessionFactory(sessionFactory().getObject());
return wrhsDao;
}
...
@Configuration
public class ScheduleConfiguration {
private static Logger logger = LoggerFactory.getLogger(ScheduleConfiguration.class);
@Autowired
private CoreConfiguration coreConfiguration;
@Bean
public HandlerMapping handlerMapping(){
DefaultAnnotationHandlerMapping mapping = new DefaultAnnotationHandlerMapping();
mapping.setInterceptors(new Object []{coreConfiguration.openSessionViewInterceptor()});
return mapping;
}
@Bean
public HandlerAdapter handerAdapter(){
return new AnnotationMethodHandlerAdapter();
}
@Bean
public ScheduleController scheduleController() throws Exception{
ScheduleController controller = new ScheduleController();
controller.setWrhsDao(coreConfiguration.getWarehouseDAO());
return controller;
}
...
在Controller中,我必须设置
@Controller
@RequestMapping
public class ScheduleController {
private static Logger logger = LoggerFactory.getLogger(ScheduleController.class);
private WarehouseDAO wrhsDao;
@RenderMapping
@RequestMapping("VIEW")
public String viewSchedule(Map<String, Object> modelMap){...}
public void setWrhsDao(WarehouseDAO wrhsDao) {
this.wrhsDao = wrhsDao;
}
}
WarehouseDAO具有@Repository注释,而SessionFactory未自动装配。
希望这可以帮助其他有类似问题的人。
答案 5 :(得分:1)
我只是添加一些花了我一些时间来调试的东西:不要忘记@Transactional注释只适用于“公共”方法。
我在“受保护的”上放了一些@Transactional并收到了这个错误。
希望有所帮助:)
http://docs.spring.io/spring/docs/3.1.0.M2/spring-framework-reference/html/transaction.html
方法可见性和@Transactional
使用代理时,应该应用@Transactional注释 仅限具有公众可见度的方法。如果你做注释保护, 使用@Transactional注释的私有或包可见方法, 没有引发错误,但带注释的方法没有出现错误 配置的事务设置。考虑使用AspectJ(参见 如果你需要注释非公开方法。