gpt4 book ai didi

java - 未找到当前线程 : Spring 3 and Hibernate 4 (Using @PostConstruct annotation) 的 session

转载 作者:行者123 更新时间:2023-11-30 03:40:51 25 4
gpt4 key购买 nike

我阅读了大量有类似问题的人的帖子,但我仍然无法使我的代码工作。

当我将 No Session found for current thread 从 Dao 移至服务层时,就会出现“@Transactional ”。事实上,我确信将事务绑定(bind)到单个访问是一种资源浪费。顺便说一下,我的网络应用程序配置非常常见:

  • Spring 3.1.2
  • hibernate 4

我无法找出问题所在,我检查了著名的 <tx:annotation-driven> 是否位于正确的位置以及正确的 <context:component-scan ...> 。我的猜测是 spring 需要将 @Transactional 也放置在具有 session 工厂引用的类之上,但这对我来说似乎有点不合逻辑。

这是servlet

<!-- auto-detects and registers annotated classes belonging to the base package-->
<context:component-scan base-package="com.x.y.controllers" />
<!-- flips on all the annotation-driven capabilities for Spring MVC -->
<mvc:annotation-driven />
...

这是上下文

<!-- enables the @Transactional annotantions -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- auto-detects and registers annotated classes belonging to the base package-->
<context:component-scan base-package="com.x.y.service" />
<context:component-scan base-package="com.x.y.aop" />
<context:component-scan base-package="com.x.y.model" />


<bean id="dataSource"
class = "com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${database.driver.className}" />
<property name="jdbcUrl" value="${database.uri}" />
<property name="user" value="${database.username}" />
<property name="password" value="${database.password}" />

<!-- these are C3P0 properties -->
<property name="checkoutTimeout" value="30000" />
<property name="initialPoolSize" value="10" />
<property name="maxIdleTime" value="30" />
<property name="minPoolSize" value="10" />
<property name="maxPoolSize" value="100" />
<property name="maxStatements" value="200" />
<property name="testConnectionOnCheckout" value="false" />
<property name="testConnectionOnCheckin" value="true" />
<property name="preferredTestQuery" value="SELECT 1" />
<property name="idleConnectionTestPeriod" value="30" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${database.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.connection.SetBigStringTryClob">true</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
</props>
</property>
</bean>

这是服务

package com.x.y.service.initialization;

@Component
public class Initializer {

@Autowired
@Qualifier("userDaoImpl")
private UserDao userDao;

@PostConstruct
@Transactional
public void init()
{
ProfiledUser admin = userDao.loadByUsername("Administrator");

...
}
}

这是DAO

package com.x.y.model.dao;

@Repository(value="userDaoImpl")
public class UserDaoImpl implements UserDao{

@Autowired
@Qualifier("sessionFactory")
protected SessionFactory sessionFactory;

public ProfiledUser loadByUsername(String username)
{
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ProfiledUser.class);
criteria.add(Restrictions.eq("username", username));
ProfiledUser user = (ProfiledUser) criteria.uniqueResult();
if(user != null)
return user;
else
return null;
}
}

这是堆栈跟踪

ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'initializer': Invocation of init method failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:135)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1448)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: 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:881)
at com.x.y.model.dao.UserDaoImpl.loadByUsername(UserDaoImpl.java:37)
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:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy15.loadByUsername(Unknown Source)
at com.x.y.service.initialization.Initializer.init(Initializer.java:46)
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.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:346)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:299)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:132)
... 29 more

最佳答案

也许它是其他答案所暗示的错误配置,但是请记住,您不应该使用 @Transactional 注释您的 @PostConstruct 并期望它能够工作。当执行 @PostConstruct 时,不能保证您的代码具有事务语义。原因是@PostConstruct仅保证所有依赖项都已注入(inject)并且bean构建已完成,但并不意味着完整的上下文已完成加载(不保证事务工具已完成)已完成)。

如果您确实需要在 @PostConstruct 中进行事务处理,请采用编程方式。这些只是我的两分钱,但很可能是您问题的原因

更新

刚刚找到一个blog关于它,他们建议使用 @PostInitialize 因为它保证在加载完整上下文后被调用

关于java - 未找到当前线程 : Spring 3 and Hibernate 4 (Using @PostConstruct annotation) 的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26866466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com