目前我试图让JPA示例使用spring boot
(http://spring.io/guides/tutorials/data/3/)。
当我使用示例中的代码时:
@Bean
public DataSource dataSource() throws SQLException {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
public EntityManagerFactory entityManagerFactory() throws SQLException {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.yummynoodlebar.persistence.domain");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
@Bean
public PlatformTransactionManager transactionManager() throws SQLException {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
我总是得到异常&#34;引起:java.lang.ClassCastException:org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean $$ EnhancerBySpringCGLIB $$ 3cbaf28d无法强制转换为javax.persistence.EntityManagerFactory&#34;。< / p>
我在自己的数据源中使用此示例:
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("user");
dataSource.setMaxTotal(5);
dataSource.setInitialSize(2);
dataSource.setPassword("pw");
dataSource.setUrl("jdbc:mysql://localhost/data");
return dataSource;
}
当我正在处理某些事情时,一切正常:
我将&#34; EntityManagerFactory&#34; -Method更改为:
public LocalContainerEntityManagerFactoryBean entityManagerFactory() ...
和transactionManager方法:
public PlatformTransactionManager transactionManager(
EntityManagerFactory emf) throws SQLException {
并通过方法变量&#34; emf&#34;直接设置EntityManagerFactory。
为什么?
有人可以向我解释为什么教程中的示例不起作用?我正在为这个项目使用mysql驱动程序。
谢谢!
此致
答案 0 :(得分:6)
这可能会有所帮助:
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
transactionManager.setDataSource(dataSource());
transactionManager.setJpaDialect(jpaDialect());
return transactionManager;
}
答案 1 :(得分:0)
尝试在XML配置中创建TransactionManager,如下所示:
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
使用注释导入:
@ImportResource("classpath*:/config.xml")