gpt4 book ai didi

java - 如何将 LocalContainerEntityManagerFactoryBean 设置为 JpaTransactionManager?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:21:37 24 4
gpt4 key购买 nike

在spring的官方文档中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;
}

It’s important to create LocalContainerEntityManagerFactoryBean and not EntityManagerFactory directly since the former also participates in exception translation mechanisms besides simply creating 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;

最佳答案

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

@Bean
public PlatformTransactionManager transactionManager() {

JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}

getObject() 方法返回单例 EntityManagerFactory

关于java - 如何将 LocalContainerEntityManagerFactoryBean 设置为 JpaTransactionManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44904340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com