Spring Boot的子项目Spring data JPA配置多数据源的那些坑儿

Spring Boot 的spring data JPA配置多数据源项目过程分析:

工程结构:

左侧为工程结构

POM.xml

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.0.4.RELEASE</version>

第一个坑儿:

实体管理器和事务管理器配置中:

修改

/*    private Map getVendorProperties(DataSource dataSource) {

return jpaProperties.getHibernateProperties(dataSource);

    }*/

private Map getVendorProperties() {

return jpaProperties.getHibernateProperties(new HibernateSettings());

}

原因:javax.sql.DataSource 不能作为 jpaProperties.getHibernateProperties的参数。

如果你Spring Boot 框架使用1.5.6版本也会报错,

@Autowired

private JpaProperties  jpaProperties;

报错说:找不到这个Bean.


第二个坑儿:

at com.potevio.platform.PlatformApplication.main(PlatformApplication.java:10) [classes/:na]

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.

百度、goolge了好久:

说什么的都有:1、有人说导入的jar包不对;

2、有人说是因为缺少Herbinate相关的jar包;

我在POM文件中加入:

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>5.1.1.RELEASE</version>

</dependency>

然后,错误变成了:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryHeatMap' defined in class path resource [com/potevio/platform/config/RepositoryHeatMapConfig.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryHeatMap' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource

可见,引入spring-jdbc是对的,但是还是有些地方不对。

继续找原因:

把有问题的源码贴出来看看:

package com.potevio.platform.config;

/**

* @program: platform

* @description: 实体管理器和事务管理器配置

* @author: fengzhenbiao

* @create: 2018-11-28 15:32

**/

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;

import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;

import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.orm.jpa.JpaTransactionManager;

import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;

import javax.sql.DataSource;

import java.util.Map;

@Configuration

@EnableTransactionManagement

@EnableJpaRepositories(

/*实体管理工厂引用名称,对应到@Bean注解对应的方法*/

        entityManagerFactoryRef="entityManagerFactoryHeatMap",

/*事务管理工厂引用名称,对应到@Bean注解对应的方法*/

        transactionManagerRef="transactionManagerHeatMap",

basePackages= {"com.potevio.platform.repository.heatMapRepository" }

)

public class RepositoryHeatMapConfig {

@Autowired

    private JpaPropertiesjpaProperties;

@Autowired

    @Qualifier("heatMapDS")

private DataSourceheatMapDS;

@Bean(name ="entityManagerHeatMap")

@Primary

    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {

return entityManagerFactoryHeatMap(builder).getObject().createEntityManager();

}

@Bean(name ="entityManagerFactoryHeatMap")

@Primary

    public LocalContainerEntityManagerFactoryBean entityManagerFactoryHeatMap (EntityManagerFactoryBuilder builder) {

return builder

.dataSource(heatMapDS)

.properties(getVendorProperties())

.packages("com.potevio.platform.domain.heatMapDomain")//设置实体类所在位置

                .persistenceUnit("primaryPersistenceUnit")

.build();

}

private Map getVendorProperties() {

return jpaProperties.getHibernateProperties(new HibernateSettings());

}

/*    private Map getVendorProperties(DataSource dataSource) {

return jpaProperties.getHibernateProperties(dataSource);

}*/

    @Bean(name ="transactionManagerHeatMap")

@Primary

    PlatformTransactionManager transactionManagerHeatMap(EntityManagerFactoryBuilder builder) {

return new JpaTransactionManager(entityManagerFactoryHeatMap(builder).getObject());

}

}

Log记录错误从这里开始:

 public LocalContainerEntityManagerFactoryBean entityManagerFactoryHeatMap (EntityManagerFactoryBuilder builder) 

继续往下看log

Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource

错误发生的地方进一步锁定在 'entityManagerFactoryBuilder' ,它的第一个参数是什么呢?

看看库里的源码:

//

// Source code recreated from a .class file by IntelliJ IDEA

// (powered by Fernflower decompiler)

//

package org.springframework.boot.orm.jpa;

import java.net.URL;

import java.util.HashMap;

import java.util.HashSet;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Set;

import javax.sql.DataSource;

import org.springframework.orm.jpa.JpaVendorAdapter;

import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;

import org.springframework.util.ClassUtils;

import org.springframework.util.ObjectUtils;

import org.springframework.util.StringUtils;

public class EntityManagerFactoryBuilder {

private final JpaVendorAdapter jpaVendorAdapter;

private final PersistenceUnitManager persistenceUnitManager;

private final Map jpaProperties;

private final URL persistenceUnitRootLocation;

private EntityManagerFactoryBuilder.EntityManagerFactoryBeanCallback callback;

public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map jpaProperties, PersistenceUnitManager persistenceUnitManager) {

this(jpaVendorAdapter, jpaProperties, persistenceUnitManager, (URL)null);

}

public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map jpaProperties, PersistenceUnitManager persistenceUnitManager, URL persistenceUnitRootLocation) {

this.jpaVendorAdapter = jpaVendorAdapter;

this.persistenceUnitManager = persistenceUnitManager;

this.jpaProperties =new LinkedHashMap(jpaProperties);

this.persistenceUnitRootLocation = persistenceUnitRootLocation;

}

public EntityManagerFactoryBuilder.Builder dataSource(DataSource dataSource) {

return new EntityManagerFactoryBuilder.Builder(dataSource);

}

public void setCallback(EntityManagerFactoryBuilder.EntityManagerFactoryBeanCallback callback) {

this.callback = callback;

}

@FunctionalInterface

public interface EntityManagerFactoryBeanCallback {

void execute(LocalContainerEntityManagerFactoryBean factory);

}

public final class Builder {

private DataSource dataSource;

private String[] packagesToScan;

private String persistenceUnit;

private Map properties;

private String[] mappingResources;

private boolean jta;

private Builder(DataSource dataSource) {

this.properties =new HashMap();

this.dataSource = dataSource;

}

public EntityManagerFactoryBuilder.Builder packages(String... packagesToScan) {

this.packagesToScan = packagesToScan;

return this;

}

public EntityManagerFactoryBuilder.Builder packages(Class... basePackageClasses) {

Set packages =new HashSet();

Class[] var3 = basePackageClasses;

int var4 = basePackageClasses.length;

for(int var5 =0; var5 < var4; ++var5) {

Class type = var3[var5];

packages.add(ClassUtils.getPackageName(type));

}

this.packagesToScan = StringUtils.toStringArray(packages);

return this;

}

public EntityManagerFactoryBuilder.Builder persistenceUnit(String persistenceUnit) {

this.persistenceUnit = persistenceUnit;

return this;

}

public EntityManagerFactoryBuilder.Builder properties(Map properties) {

this.properties.putAll(properties);

return this;

}

public EntityManagerFactoryBuilder.Builder mappingResources(String... mappingResources) {

this.mappingResources = mappingResources;

return this;

}

public EntityManagerFactoryBuilder.Builder jta(boolean jta) {

this.jta = jta;

return this;

}

public LocalContainerEntityManagerFactoryBean build() {

LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =new LocalContainerEntityManagerFactoryBean();

if (EntityManagerFactoryBuilder.this.persistenceUnitManager !=null) {

entityManagerFactoryBean.setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager);

}

if (this.persistenceUnit !=null) {

entityManagerFactoryBean.setPersistenceUnitName(this.persistenceUnit);

}

entityManagerFactoryBean.setJpaVendorAdapter(EntityManagerFactoryBuilder.this.jpaVendorAdapter);

if (this.jta) {

entityManagerFactoryBean.setJtaDataSource(this.dataSource);

}else {

entityManagerFactoryBean.setDataSource(this.dataSource);

}

entityManagerFactoryBean.setPackagesToScan(this.packagesToScan);

entityManagerFactoryBean.getJpaPropertyMap().putAll(EntityManagerFactoryBuilder.this.jpaProperties);

entityManagerFactoryBean.getJpaPropertyMap().putAll(this.properties);

if (!ObjectUtils.isEmpty(this.mappingResources)) {

entityManagerFactoryBean.setMappingResources(this.mappingResources);

}

URL rootLocation = EntityManagerFactoryBuilder.this.persistenceUnitRootLocation;

if (rootLocation !=null) {

entityManagerFactoryBean.setPersistenceUnitRootLocation(rootLocation.toString());

}

if (EntityManagerFactoryBuilder.this.callback !=null) {

EntityManagerFactoryBuilder.this.callback.execute(entityManagerFactoryBean);

}

return entityManagerFactoryBean;

}

}

}


应该是缺少一个Baen    jpaVendorAdapter

@Bean

@Primary

public JpaVendorAdapter jpaVendorAdapter() {

HibernateJpaVendorAdapter adapter =new HibernateJpaVendorAdapter();

adapter.setDatabase(Database.MYSQL);

adapter.setShowSql(false);

adapter.setGenerateDdl(true);

adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");

return adapter;

}


由接近真相了

注意要修改配置文件中的url---->jdbc-url


一个大神的经验

然后:


拦截器报错

考虑配置有问题:


修改

修改:去掉@Primary

成功!


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容