2017-06-15 47 views
0

我正在嘗試創建Java應用程序,並且無法使@Transactional註釋工作。@Transactional不能使用SessionFactory

我有例如PaymentDao類:

import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Transactional; 

@Repository 
public class PaymentDao { 

private SessionFactory sessionFactory; 

@Autowired 
public PaymentDao(SessionFactory sessionFactory) { 
    this.sessionFactory = sessionFactory; 
} 

@Transactional 
public void add(Payment payment) { 
     sessionFactory.getCurrentSession() 
       .save(payment); 
     if (payment != null) throw new RuntimeException(); 
     sessionFactory.getCurrentSession() 
       .save(payment); 

     } 
} 

而且,儘管的RuntimeException被拋出時,第一個目的是始終保存到數據庫中。
我注意到,當我嘗試這樣做的:

public void add(Payment payment) { 
    try { 
     sessionFactory.getCurrentSession().getTransaction().begin(); 
     sessionFactory.getCurrentSession() 
       .save(payment); 
     if (payment != null) throw new RuntimeException(); 
     sessionFactory.getCurrentSession() 
       .save(payment); 
     sessionFactory.getCurrentSession().getTransaction().commit(); 
    } catch(RuntimeException e) { 

    sessionFactory.getCurrentSession().getTransaction().rollback(); 
    } 
} 

它的工作原理,並沒有實體被保存。

不應該@Transactional註釋的工作原理是什麼?我錯過了什麼? 這裏是我的配置類:

@Configuration 
@EnableTransactionManagement 
public class Config { 

@Bean 
public SessionFactory sessionFactory(HibernateEntityManagerFactory 
hemf){ 
    return hemf.getSessionFactory(); 
    } 
} 

編輯: 我是從服務調用它:

@Service 
public class PaymentService { 

@Autowired 
private PaymentDao paymentDao; 

public void add(PaymentDto paymentDto) throws IOException { 
    Payment payment = paymentDto.toEntity(); 
    paymentDao.add(payment); 
} 
} 

這是自動裝配到控制器。

Hibernate的配置很簡單:

spring.datasource.url= jdbc:postgresql://localhost:5432/testT 
spring.datasource.username=postgres 
spring.datasource.password=admin1 
spring.jpa.properties.hibernate.hbm2ddl.import_files_sql_extractor 
=org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor 

spring.jpa.properties.hibernate.current_session_context_class 
=org.springframework.orm.hibernate4.SpringSessionContext 

spring.jpa.hibernate.ddl-auto=create-drop 
logging.level.org.springframework.transaction.interceptor=TRACE 
+0

在完全獨立的說明中,您正在編寫的變體的DAO邏輯可以由Spring Data爲您自動生成。 – chrylis

+0

是的,我知道,但我現在只是在學習,並嘗試瞭解其他方式。 – Besanouno

+0

@Besanouno你在哪裏調用add方法? –

回答

0

您需要創建TransactionManager和準SessionFactoryDataSourceSessionFactory使用該TransactionManager

相關問題