我试图创建Java应用程序,但无法使@Transactional注释工作。
我有一个例子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 :(得分:0)
您需要创建TransactionManager
并将SessionFactory
正在使用的DataSource
或SessionFactory
关联到TransactionManager
。