In oficial documentation of spring this write next:
@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;
  }
and
It’s important to create LocalContainerEntityManagerFactoryBean and not EntityManagerFactory directly since the former also participates in exception translation mechanisms besides simply creating EntityManagerFactory.
But when I tried use it I get error:
setEntityManagerFactory
(javax.persistence.EntityManagerFactory)
in JpaTransactionManager cannot be applied
to
(org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean)
it is my imports:
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;
Your configuration looks correct. Only change your transactionManager definition as below:
@Bean
public PlatformTransactionManager transactionManager() {
  JpaTransactionManager txManager = new JpaTransactionManager();
  txManager.setEntityManagerFactory(entityManagerFactory().getObject());
  return txManager;
}
The getObject() method return singleton EntityManagerFactory.
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory 
entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
}
Construct your JpaTransactionManager with an EntityManagerFactory coming in as parameter from your @Bean. Spring will automatically create one from the LocalContainerEntityManagerFactoryBean when needed. This avoids ever calling the getObject()-method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With