gpt4 book ai didi

java - Swing + Spring + @Transactional = 不启动事务

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:29 25 4
gpt4 key购买 nike

我正在研究在 Swing 应用程序上使用 Spring 的可能性,应用 MVC 概念。

现在我尝试创建一个 @Transactional 方法,但它不会启动事务。

这是我的代码:

@Component
public class MainFormController {

@Autowired
private MainFormFrameView view;

@Autowired
private MyService service;

public MainFormController() {
view.button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doSomethingInTransaction();
}
});
}

@Transactional
public void doSomethingInTransaction() {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("No active transaction!!!!");
}
service.doSomethingOverTheTransaction();
}
}

这是我的配置:

@Configuration
@ComponentScan(basePackages = "br.com.jjw.pdv")
@EnableTransactionManagement
public class AppContextConfiguration {

@Bean
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource ret = new ComboPooledDataSource();

ret.setDriverClass(jdbcDriver.class.getName());
ret.setJdbcUrl("jdbc:hsqldb:file:dados.hsql");
ret.setUser("sa");
ret.setPassword("");

return ret;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws PropertyVetoException {
LocalContainerEntityManagerFactoryBean ret = new LocalContainerEntityManagerFactoryBean();
ret.setDataSource(dataSource());
ret.setJpaDialect(jpaDialect());

EclipseLinkJpaVendorAdapter adapter = new EclipseLinkJpaVendorAdapter();
adapter.setDatabase(Database.HSQL);

ret.setJpaVendorAdapter(adapter);
ret.setPersistenceXmlLocation("classpath:META-INF/persistence.xml");
ret.setPersistenceUnitName("jjw-pdv-unit");
ret.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());

return ret;
}

@Bean
public JpaDialect jpaDialect() {
return new EclipseLinkJpaDialect();
}

@Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}

@Bean
public JpaTransactionManager transactionManager() throws PropertyVetoException {
JpaTransactionManager ret = new JpaTransactionManager();
ret.setEntityManagerFactory(entityManagerFactory().getNativeEntityManagerFactory());
ret.setJpaDialect(jpaDialect());
return ret;
}

}

当我单击按钮时,doSomethingInTransaction() 方法引发异常:

 IllegalStateException("No active transaction!!!!");

为什么?

最佳答案

Spring AOP 基于代理,不建议进行内部调用。

您需要在 spring 提供的代理上进行调用,例如

 SomeTransactionalBean bean = 
applicationContext.getBean(SomeTransactionalBean.class);

bean.doSomethingInTrasanction();

例如,在服务方法上添加@Transactional注解。

关于java - Swing + Spring + @Transactional = 不启动事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22531728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com