我试图通过JPA和Spring数据与MySQL数据库进行事务交互。
配置
@Configuration
@EnableJpaRepositories("com.some.models.repositories")
@EnableTransactionManagement
public class MegabotsConfiguration {
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setJpaProperties(additionalProperties());
factory.setPackagesToScan(new String[] { "com.datarank.megabots.models.entities", "com.datarank.megabots.models.repositories" });
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/local_ttaggdb");
dataSource.setUsername( "root" );
dataSource.setPassword( "" );
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
//...
}
在这里,我试图使用交易:
@Repository
@Scope("prototype")
@Transactional
public class BotWorkQueueRepository {
@Autowired
private BotWorkQueueJPARepository botWorkQueueJPARepository; //this is the jparepository referenced in the @EnableJpaRepositories in config
@PersistenceContext
private EntityManager entityManager;
@Transactional
public synchronized void flagInFlight(final List<BotWorkQueueEntity> botWorkQueueEntities) {
try {
//...set a few properties on entities, then
entityManager.flush(); //Exception thrown here
entityManager.clear();
} catch (Exception e) {
LOGGER.warn("Error making in flight: " + e);
}
}
}
我得到的错误:
javax.persistence.TransactionRequiredException: No transactional EntityManager available
我已尝试在SO中发布此错误的大多数解决方案,但没有成功。
答案 0 :(得分:0)
首发一件事, 在maven中,如果您使用的是appassembler-maven-plugin,请将以下行添加到POM文件中的plugin.configuration标记中。
<extraJvmArguments>-javaagent:"$REPO"/org/aspectj/aspectjweaver/1.8.5/aspectjweaver-1.8.5.jar</extraJvmArguments>
如果您在IDE中运行,请将以下行添加到VM参数中。
-javaagent:<PATH TO MAVEN REPO>/org/aspectj/aspectjweaver/1.8.5/aspectjweaver-1.8.5.jar
maven repo的路径可能类似于/User/kenny/.m2/repository/
。
$REPO
将在POM文件中自动解析。