-1
我有一個使用Spring JPA的應用程序,並使用@Async spring批註執行一些後臺進程。該過程需要將參數保存在數據庫中,或者如果它已經存在,則更新數據庫。Spring JPA:從異步方法處理數據時未保存到數據庫
這不能正常工作,因爲我的數據實體在@Async方法完成後沒有在數據庫中持久化。但是當我從方法中刪除@Async註釋時,所有的事情都可以正常工作。我的數據保存或更新到數據庫。
有沒有人有一個想法什麼可能是錯的,或者我可能會失蹤?
謝謝。
** UPDATE [代碼示例]
ASYNCSERVICE
@Service
@EnableAsync
class AsyncService() {
@Async
public void process(firstEntity, secondEntity) {
firstEntity = prepareParams(firstEntity);
secondEntity = prepareParams(secondEntity);
save(firstEntity, secondEntity);
}
}
ENTITYRELATIONSERVICE
@Transactional
@Service
class EntityRelationService() {
private SecondEntityRepo secondEntityRepo;
@Autowired
public EntityRelationService(SecondEntityRepo secondEntityRepo) {
this.secondEntityRepo = secondEntityRepo;
}
@Transactional
public void save(p1, p2) {
p2.setRelation(p1);
this.secondEntityRepo(p2);
}
}
BEAN CONFIG
@Bean
@Primary
@ConfigurationProperties(prefix = "app.database")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
@Primary
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
sf.setDataSource(dataSource());
sf.setPackagesToScan("com.app");
Properties props = new Properties();
props.put("hibernate.use_sql_comments", false);
props.put("hibernate.show_sql", true);
sf.setHibernateProperties(props);
return sf;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
你可以發佈代碼和spring bean的配置和設置嗎? – yaswanth
請提供[MCVE](https://stackoverflow.com/help/mcve)。 –