Spring MVC 3 + Hibernate 4交易问题

时间:2019-02-28 17:47:31

标签: spring hibernate

我使用Spring MVC 3 e Hibernate 4开始了一个项目,但是我在使用mysql进行交易时遇到了问题,我尝试使用@transational和XML,但是这两种配置都不起作用,我也不想这样做每种方法。

我有一个服务层,想要启动事务以从此处访问必需的DAO,但是该事务从未打开。

显然,Spring不会启动事务,而hibernate负责打开连接。

@Service("userService") @Transactional

        public class UserService {
        @Autowired
        private HBUsuario hDaoUsuario;
        public UserService() {  }

         @Transactional(propagation=Propagation.REQUIRED,
         isolation=Isolation.DEFAULT, timeout=120)  
        public Usuario saveUsuario(String username, String password, String nome, String role) throws Exception{

            Usuario user = new Usuario(username, password, nome);           
            hDaoUsuario.persistir(user);
            return user;
        }

        public HBUsuario gethDaoUsuario() {
            return hDaoUsuario;
        }

        public void sethDaoUsuario(HBUsuario hDaoUsuario) {
            this.hDaoUsuario = hDaoUsuario;
        }
    }

HBUsuario

@Transactional(propagation = Propagation.SUPPORTS)
@Repository("hDaoUsuario")
public class HBUsuario extends HBDAO<Usuario> {

    protected Class getClazz() {
        return Usuario.class;
    }


     public void persistir(Usuario objeto) throws Exception {
        getSession().saveOrUpdate(objeto); }
}

HBDao

@Transactional(propagation=Propagation.SUPPORTS)
public abstract class HBDAO<T> {

    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sf) {
        sessionFactory = sf;
    }


    protected Session getSession() throws Exception {
        Session session = getSessionFactory().getCurrentSession();
        /* comentado para  não usar na mão
         * try{ if(!session.isConnected()) return getSession(session, 0); else{
         * if(!session.getTransaction().isActive()) session.beginTransaction();
         * if(!session.getTransaction().isActive()) return getSession(session, 0); //}
         * 
         * } catch(Exception e){ e.printStackTrace(); return getSession(session, 0); }
         */ // Logar.info("\n*********\nSessão de Banco já disponível no Pool
            // \n*********\n");
        return session;
    }

春季数据

<beans default-autowire="byType"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

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

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="javax.persistence.validation.mode">none</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <!-- usado para o hibernate -->
        <property name="annotatedClasses">
            <array>
                <value>br.com.becb.icontador.Model.Usuario</value>

            </array>
        </property>

    </bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- property name="jdbcUrl" value="${jdbc.url}" / -->
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/icontador" />
        <property name="properties">
            <props>
                <prop key="c3p0.min_size">3</prop>
                <prop key="hc3p0.maxPoolSize">20</prop>
                <prop key="hc3p0.timeout">30000</prop>
                <prop key="c3p0.acquire_increment">3</prop>
                <prop key="c3p0.acquire_rentry_attemps">3</prop>
                <prop key="c3p0.max_statements">50</prop>
                <prop key="c3p0.testConnectionOnCheckout">true</prop>
                <prop key="hibernate.c3p0.idle_test_period">100</prop>
                <prop key="c3p0.preferredTestQuery">SELECT  1;  </prop>
                <prop key="hibernate.c3p0.testConnectionOnCheckout">true</prop>
                <prop key="hibernate.connection.release_mode">after_transaction </prop>
                <prop key="user">root</prop>
                <prop key="password">root</prop>
                <!-- prop key="user">${jdbc.username}
            </prop>
                <prop key="password">${jdbc.password}</prop -->
            </props> 
        </property>
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
    </bean>
<tx:advice id="txAdvice"
        transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"
                isolation="SERIALIZABLE" />
            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
<aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* br.com.becb.icontador.servicos.*.*(..))"/>

    </aop:config>
</beans>

错误1 org.hibernate.HibernateException:没有活动的事务,saveOrUpdate无效

错误2 没有<prop key="hibernate.current_session_context_class">thread</prop> org.hibernate.HibernateException:未找到当前线程的会话

0 个答案:

没有答案