如何将LocalContainerEntityManagerFactoryBean设置为JpaTransactionManager?

use*_*472 4 java spring hibernate spring-data-jpa

在春季的官方文档中,其内容如下

@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;
  }
Run Code Online (Sandbox Code Playgroud)

重要的是创建LocalContainerEntityManagerFactoryBean而不是直接创建EntityManagerFactory,因为前者除了简单地创建EntityManagerFactory之外,还参与异常转换机制。

但是当我尝试使用它时,我得到了错误:

setEntityManagerFactory
(javax.persistence.EntityManagerFactory)
in JpaTransactionManager cannot be applied
to
(org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean)
Run Code Online (Sandbox Code Playgroud)

这是我的进口:

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;
Run Code Online (Sandbox Code Playgroud)

San*_*ose 7

您的配置看起来正确。只需如下更改您的transactionManager定义:

@Bean
public PlatformTransactionManager transactionManager() {

  JpaTransactionManager txManager = new JpaTransactionManager();
  txManager.setEntityManagerFactory(entityManagerFactory().getObject());
  return txManager;
}
Run Code Online (Sandbox Code Playgroud)

getObject()方法返回单例EntityManagerFactory