【问题标题】:Spring Transaction Hibernate @Transaction annotation not working with @AutowiredSpring Transaction Hibernate @Transaction 注解不适用于@Autowired
【发布时间】:2016-04-21 10:41:22
【问题描述】:

Spring Transaction Hibernate @Transaction 注解无法正确使用 @Autowired。如果我创建Dao`` element byxml(UserDao2 userDao2)`,

Service 类中的事务注解正在工作,如果它在尝试 getCurrentSesion 时通过 Dao 类中的 @Repository 注解表示:

org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) ~[spring-orm-3.2.8.RELEASE.jar:3.2.8.RELEASE]
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:993) ~[hibernate-core-4.2.11.Final.jar:4.2.11.Final]

看来@Transactional 注释与会话工厂的链接不好

库版本:

<jdk.version>1.6</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<hibernate.version>4.2.11.Final</hibernate.version>

spring-database.xml

<context:annotation-config />

 <jee:jndi-lookup id="datasourcenn" jndi-name="java:/comp/env/nn_datasource" /> 

    <bean id="sesionHibernate"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="dataSource" ref="datasourcenn"/>

        <property name="packagesToScan" value="com.web.entity"/>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</prop>            
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>

                        <!-- nuevas properties de configuración -->
                <prop key="hibernate.c3p0.min_size">5</prop>
                <prop key="hibernate.c3p0.max_size">50</prop>
                <prop key="hibernate.c3p0.timeout">300</prop>
                <prop key="hibernate.c3p0.max_statements">50</prop>

                <prop key="hibernate.bytecode.provider">cglib</prop>                                    
            </props>
        </property>
    </bean>    

    <bean id="us" class="com.web.dao.UserDaoImpl">
        <property name="sesionHibernate" ref="sesionHibernate" />
    </bean>
    <!--  -->
    <bean id="userDao2" class="com.web.dao.UserDao2Impl">
        <property name="sesionHibernate" ref="sesionHibernate" />
    </bean>



    <bean id="myUserDetailsService" class="com.web.service.UsuarioServiceImpl">
        <property name="userDao" ref="us" />
    </bean> 
    <!--
    proxy-target-class="true"  mode="aspectj" 
    -->

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

    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

UserDao2(如果我通过 xml 创建 @Repository,我会删除它)

@Repository
public class UserDao2Impl implements UserDao2 {
  private static Logger log = LoggerFactory.getLogger(UserDao2Impl.class);

  @Autowired
  @Qualifier("sesionHibernate")
  private SessionFactory sesionHibernate;

  @SuppressWarnings("unchecked")
  public Usuario findByUserName(String username) {
    try {
      log.info("findByUserName" + sesionHibernate);

      List<Usuario> users = new ArrayList<Usuario>();
      System.out.println(sesionHibernate+"\n----------");

      users = sesionHibernate.getCurrentSession().createQuery("from Usuario where nombre=?").setParameter(0, username).list();
      // users = sesionHibernate.getCurrentSession().createQuery("from Usuario
      // where nombre=?").setParameter(0, username).list();

      if (users.size() > 0) {
        return users.get(0);
      } else {
        return null;
      }

    } catch (Exception e) {
      log.error("findByUserName ", e);
      return null;
    }
  }

Usuario2ServiceImpl如果有@Transacional的服务

@Service 
@Transactional
public class Usuario2ServiceImpl implements Usuario2Service {
  private static Logger log = LoggerFactory.getLogger(Usuario2ServiceImpl.class);

  //Qualifier("userDaoImpl")
  @Autowired
  private UserDao2 userDao2;       

  @Override
  public com.web.entity.Usuario getUsuariodetalles(final String nombreUsuario) throws UsernameNotFoundException {
    log.info("getUsuariodetalles - 1");
    System.out.println("ssss"+userDao2);
    com.web.entity.Usuario usuario = userDao2.findByUserName(nombreUsuario);    

    log.info("getUsuariodetalles - 2");
    return usuario;   
  }

【问题讨论】:

  • 您同时拥有@Service&lt;bean&gt;
  • 不,bean 用于另一个类 UsuarioServiceImpl,@Service 用于 UsuarioService2Impl
  • 我猜你有一个ContextLoaderLIstener,它加载了spring-database.xml,你有一个DispatcherServlet,它加载了其他东西,其中包含一个&lt;context:component-scan /&gt;....

标签: java spring hibernate spring-mvc transactions


【解决方案1】:

您是否尝试将@Transactional 注释放在服务层方法中,您已将其放在类上。我认为它应该工作。

【讨论】:

  • 我试图把@Transactional放在服务的接口上,在被调用的函数上,在函数的接口上,到处都是,我仍然得到同样的错误。
【解决方案2】:

我在 Tomcat 中通过在下一行输入 spring-database.xml 解决了这个问题:

<context:load-time-weaver aspectj-weaving="autodetect"/>

但它在 JBoss 中不起作用,这是我需要部署最终版本的地方。其他解决方案?

在 Jboss 中,我需要在 xml(Service 和 Dao)中创建这两个东西,保持事务性注释。但是如果使用@Repository 或@Service 创建它们(dao 和服务),我将无法工作。

【讨论】:

    【解决方案3】:

    解决方案,我添加到 mvc-dispatcher-servlet.xml, mvc:interceptors 配置以打开与 org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor 的会话。只需要在属性中定义sessionFactory即可。

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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/mvc 
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            ">
        <context:annotation-config />
        <context:component-scan base-package="com.web" />
    
        <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <bean name="OpenSessionInViewInterceptorCom" class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor">
                    <property name="sessionFactory">
                        <ref bean ="sesionHibernate" />
                    </property>
                </bean>
            </mvc:interceptor>
        </mvc:interceptors>
    
        <!-- Configures the @Controller programming model -->
    
        <mvc:annotation-driven />
        <mvc:resources mapping="/css/**" location="/css/" />
        <mvc:resources mapping="/img/**" location="/img/" />
        <mvc:resources mapping="/js/**" location="/js/" />
    
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix">
                <value>/WEB-INF/pages/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>
    
    
    
    </beans>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多