2014-09-02 4 views
2

Я хочу использовать transactionManager весны. Моя конфигурация весной здесь:@transactional не работает весна 4 hibernate 4

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-4.0.xsd 
     "> 


<bean id="dataSource" 
     class="org.apache.commons.dbcp.BasicDataSource" 
     depends-on="propertyPlaceholderConfigurer" 
     p:driverClassName="org.postgresql.Driver" 
     p:url="${db.url}" 
     p:username="${db.username}" 
     p:password="${db.password}" 
     destroy-method="close" /> 




<context:spring-configured /> 
<context:annotation-config /> 

<bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 
     depends-on="flywayAutomaticMigrationBean"> 
    <property name="dataSource" ref="dataSource" /> 
    <property name="packagesToScan" value="com.example" /> 
    <property name="hibernateProperties"> 
     <props> 
      <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> 
      <prop key="hibernate.show_sql">false</prop> 
      <prop key="hibernate.default_schema">restProj</prop> 
     </props> 
    </property> 

    <property name="mappingResources"> 
     <list> 
      <value>com/example/db/hbm/user/AuthUser.hbm.xml</value> 
      <value>com/example/db/hbm/user/User.hbm.xml</value> 
      <value>com/example/db/hbm/user/Role.hbm.xml</value> 
      <value>com/example/db/hbm/user/Feature.hbm.xml</value> 

     </list> 
    </property> 
</bean> 

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

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

<context:component-scan base-package="com.example.model" > 
    <context:include-filter type="regex" expression=".*\.dao\..*DAO"/> 
    <context:include-filter type="regex" expression=".*\.logic\..*Mgr"/> 
</context:component-scan> 
<context:component-scan base-package="com.example.commons" > 
    <context:include-filter type="regex" expression=".*\.dao\..*DAO"/> 
    <context:include-filter type="regex" expression=".*\.logic\..*Mgr"/> 
</context:component-scan> 


</beans> 

И это один из моего класса менеджер:

import org.springframework.transaction.annotation.Transactional; 

public class UserMgr extends BaseUserMgr { 

    @Transactional (rollbackFor = Exception.class) 
    public void checkTransaction(){ 
     Feature feature = new Feature(); 
     feature.setExtuid(UUID.randomUUID().toString()); 
     feature.setName("boogh"); 
     feature.setDescription("salam"); 
     FeatureDAO.getInstance().save(feature); 
    } 
} 

Когда я бегу UserMgr.checkTransaction() данные не сохраняются. Может ли кто-нибудь объяснить мне, что не так?

__UPDATE___

Это мой FeatureDao Сохранить метод:

 public java.lang.Long save(com.example.model.user.Feature feature) 
     throws org.hibernate.HibernateException { 
     return (java.lang.Long) super.save(feature); 
    } 

и это суперкласс Сохранить метод:

protected Serializable save(final Object obj) { 
    return save(obj, getSession()); 
} 

и метод getSession() получить сеанс от весеннего SessionFactory ,

И это мой метод FeatureDao деЫпзЬапс():

public static com.model.user.dao.FeatureDAO getInstance() { 
    return com.example.core.spring.ApplicationContextUtil.getApplicationContext().getBean(com.example.model.user.dao.FeatureDAO.class); 
} 
+1

Я думаю, что ваш FeatureDAO не Spring боб => это не обернуто Spring AOP => он управляет сеансами и транзакциями независимо, не обращаясь к транзакциям Spring. ** Пожалуйста, добавьте исходный код FeatureDAO, для ответа на этот вопрос **. –

+0

FeatureDao - это загрузка в <контексте: компонент-сканирование base-package = "com.example.model"> <контекст: include-filter type = "regex" выражение = ". * \. Logic \ .. * Mgr" />

+0

Я обновил сообщение. :) –

ответ

0

В вашем случае Spring собирается использовать JDK прокси по умолчанию. Для этого вам потребуется @Transactional на уровне интерфейса.

Чтобы включить использование @Transactional на уровне класса вы можете настроить Spring использовать CGLIB прокси следующим

<tx:annotation-driven transaction-manager="transactionManager" 
proxy-target-class="true" /> 

Подробнее here

Смежные вопросы