在春天this的正式文件中写下:
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.acme.domain");
factory.setDataSource(dataSource());
return factory;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
和
创建LocalContainerEntityManagerFactoryBean和 不是EntityManagerFactory,因为前者也参与其中 在除了简单创建之外的异常翻译机制 EntityManagerFactory的。
但是当我尝试使用它时,我收到错误:
setEntityManagerFactory
(javax.persistence.EntityManagerFactory)
in JpaTransactionManager cannot be applied
to
(org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean)
这是我的进口商品:
import org.apache.tomcat.jdbc.pool.DataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
答案 0 :(得分:5)
您的配置看起来是正确的。仅更改您的transactionManager定义,如下所示:
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
getObject()
方法返回单一EntityManagerFactory
。
答案 1 :(得分:1)
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory
entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
使用来自@Bean的EntityManagerFactory作为参数来构造JpaTransactionManager。必要时,Spring将自动从LocalContainerEntityManagerFactoryBean创建一个。这样可以避免调用getObject()方法。