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
在完全独立的说明中,您正在编写的变体的DAO逻辑可以由Spring Data为您自动生成。 – chrylis
是的,我知道,但我现在只是在学习,并尝试了解其他方式。 – Besanouno
@Besanouno你在哪里调用add方法? –