Spring Transaction Hibernate @Transaction注释不能与@Autowired一起使用

时间:2016-04-21 10:41:22

标签: java spring hibernate spring-mvc transactions

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

Service类中的事务性anotation正在运行,如果在尝试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>

弹簧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;   
  }

3 个答案:

答案 0 :(得分:0)

您是否尝试在服务层方法中添加@Transactional注释,您已将其放在课堂上。我认为它应该有效。

答案 1 :(得分:0)

我通过放入spring-database.xml下一行解决了Tomcat的问题:

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

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

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

答案 2 :(得分:0)

解决方案,我添加到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>