Estou iniciando um projeto com Spring MVC 3 e Hibernate 4, o problema está na implementação da transações, tentei inicialmente com @transational e acabei voltando pra xml, porém nenhuma delas funcionou e não quero gerencia-las na mão.
Quero gerenciar a transação a partir da camada de serviço e assim ir pelos DAOs necessários até completa-las, porém essa transação nunca é aberta.
Aparentemente o Spring não inicia a transação, fazendo com que o hibernate fique responsável pela abertura da sessão.
@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); }
}
@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;
}
spring-data.xml
<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>
O erro 1:
org.hibernate.HibernateException: saveOrUpdate is not valid without active transaction
Erro 2
e quando tiro a linha <prop key="hibernate.current_session_context_class">thread</prop>
org.hibernate.HibernateException: No Session found for current thread