当前位置: 首页 > 知识库问答 >
问题:

Spring boot data jpa multiple datasources entityManagerFactory错误

强才捷
2023-03-14

我想在Spring Boot中使用两个数据库。代码如下:

@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories(
        basePackages = {"net.elyland.pipe.repositories.router"},
        entityManagerFactoryRef = "routerEntityManagerFactory",
        transactionManagerRef = "routerTransactionManager")
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = {"net.elyland.pipe.domain.router"})
public class RouterRepositoryConfiguration {

    @Bean(name = "routerDataSource")
    @ConfigurationProperties(prefix = "router.datasource")
    public DataSource routerDataSource() {
        return DataSourceBuilder
                .create()
                .build();
    }

    @PersistenceContext(unitName = "routerPU")
    @Bean(name = "routerEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean routerEntityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("routerDataSource")DataSource routerDataSource) {
        return builder
                .dataSource(routerDataSource)
                .properties(hibernateProperties())
                .packages(Ip.class, Net.class, Provider.class, QueueRule.class, QueueType.class,RemoteIp.class,Subnet.class,TrafficQueue.class)
                .persistenceUnit("routerPU")
                .build();
    }

    @Bean(name = "routerTransactionManager")
    public PlatformTransactionManager mysqlTransactionManager(@Qualifier("routerEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    private Map hibernateProperties() {

        Resource resource = new ClassPathResource("routerHibernate.properties");

        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);

            return properties.entrySet().stream()
                    .collect(Collectors.toMap(
                            e -> e.getKey().toString(),
                            e -> e.getValue())
                    );
        } catch (IOException e) {
            return new HashMap();
        }
    }
}
@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories(
        basePackageClasses = {SshUser.class, User.class, Role.class},
        basePackages = {"net.elyland.pipe.domain.admin"},
        entityManagerFactoryRef = "adminEntityManager" ,
        transactionManagerRef = "adminTransactionManager"
        )
@EnableTransactionManagement
@PropertySource({ "classpath:application.properties" })
public class AdminRepositoryConfiguration {

    @Primary
    @Bean(name = "adminDataSource")
    @ConfigurationProperties(prefix = "admin.datasource")

    public DataSource adminDataSource() {
        System.out.println("Create datasource Admin");
        return DataSourceBuilder
                .create()
                .build();
    }

    @Primary
    @Bean(name = "adminEntityManager")
    public LocalContainerEntityManagerFactoryBean adminEntityManager(EntityManagerFactoryBuilder builder, @Qualifier("adminDataSource") DataSource adminDataSource) {
        return builder
                .dataSource(adminDataSource)
                .properties(hibernateProperties())
                .packages(User.class, LocalIp.class, CommandLog.class, PipeSize.class, Role.class,Rule.class,Server.class,SshUser.class)
                .persistenceUnit("adminPU")
                .build();
    }

    @Primary
    @Bean(name = "adminTransactionManager")
    public PlatformTransactionManager adminTransactionManager(@Qualifier("adminEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    private Map hibernateProperties() {

        Resource resource = new ClassPathResource("hibernate.properties");

        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);

            return properties.entrySet().stream()
                    .collect(Collectors.toMap(
                            e -> e.getKey().toString(),
                            e -> e.getValue())
                    );
        } catch (IOException e) {
            return new HashMap();
        }
    }
}

存储库1:

@Repository
@Transactional("adminTransactionManager")
public interface SshUserRepository extends JpaRepository<SshUser, Integer> {
    SshUser findByUsername(String username);
}

存储库2:

@Repository
@Transactional("routerTransactionManager")
public interface SubnetRepository extends JpaRepository<Subnet, Integer> {
    public Subnet findByAddress(Integer address);
    public Subnet findByMask(Integer mask);
}

属性文件:

admin.datasource.url= jdbc:mysql://192.168.10.3:3306/pipe?autoReconnect=true&useSSL=false
admin.datasource.username=user
admin.datasource.password=pass
admin.datasource.driverClassName=com.mysql.jdbc.Driver

router.datasource.url= jdbc:mysql://192.168.10.3:3306/router?autoReconnect=true&useSSL=false
router.datasource.username=user
router.datasource.password=pass
router.datasource.driverClassName=com.mysql.jdbc.Driver
#spring.jpa.show-sql = true
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=create-drop
***************************
APPLICATION FAILED TO START
***************************

Description:

Field userRepository in net.elyland.pipe.services.UserDetailsServiceImpl required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.1.RELEASE)

2017-07-07 18:52:18.774  INFO 11870 --- [           main] n.e.pipe.SpringBootMvcJspApplication     : Starting SpringBootMvcJspApplication on adm-imaterynko with PID 11870 (/home/imaterynko/SVN/sysadm/javawebdev/pipe/target/classes started by imaterynko in /home/imaterynko/SVN/sysadm/javawebdev/pipe)
2017-07-07 18:52:18.780  INFO 11870 --- [           main] n.e.pipe.SpringBootMvcJspApplication     : No active profile set, falling back to default profiles: default
2017-07-07 18:52:18.859  INFO 11870 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6a472554: startup date [Fri Jul 07 18:52:18 EEST 2017]; root of context hierarchy
2017-07-07 18:52:20.485  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'remoteIpRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:20.487  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'providerRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:20.488  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'netRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:20.491  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'queueTypeRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:20.492  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'ipRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:20.494  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'subnetRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:20.497  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'queueRuleRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:20.504  INFO 11870 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'trafficQueueRepository' with a different definition: replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-07-07 18:52:21.046  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.110  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.158  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration' of type [class org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration$$EnhancerBySpringCGLIB$$ee2486b5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.170  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'objectPostProcessor' of type [class org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.172  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@678040b3' of type [class org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.180  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration' of type [class org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerBySpringCGLIB$$12f92967] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.193  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [class org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.203  INFO 11870 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$5576be7b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-07 18:52:21.537  INFO 11870 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-07 18:52:21.551  INFO 11870 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-07-07 18:52:21.552  INFO 11870 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-07-07 18:52:22.039  INFO 11870 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2017-07-07 18:52:22.042  INFO 11870 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-07-07 18:52:22.042  INFO 11870 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3185 ms
2017-07-07 18:52:22.239  INFO 11870 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-07 18:52:22.240  INFO 11870 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-07-07 18:52:22.241  INFO 11870 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Filter characterEncodingFilter was not registered (possibly already registered?)
2017-07-07 18:52:22.241  INFO 11870 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
Create datasource Admin
2017-07-07 18:52:22.894  INFO 11870 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'adminPU'
2017-07-07 18:52:22.912  INFO 11870 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: adminPU
    ...]
2017-07-07 18:52:22.971  INFO 11870 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.11.Final}
2017-07-07 18:52:22.973  INFO 11870 --- [           main] org.hibernate.cfg.Environment            : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.MySQL5Dialect, hibernate.bytecode.use_reflection_optimizer=false, hibernate.hbm2ddl.auto=create-drop}
2017-07-07 18:52:22.974  INFO 11870 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-07-07 18:52:23.007  INFO 11870 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-07-07 18:52:23.210  INFO 11870 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-07-07 18:52:23.673  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-07 18:52:23.685 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table command_log drop foreign key FKo5wo2sqahur6v6uym1t2sjken
2017-07-07 18:52:23.685 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'pipe.command_log' doesn't exist
2017-07-07 18:52:23.688 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table host drop foreign key FK9hlhx55t325whiraf8newuxcv
2017-07-07 18:52:23.688 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'pipe.host' doesn't exist
2017-07-07 18:52:23.689 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table rule drop foreign key FKeuk4g8c1yhpjno3suq3syen02
2017-07-07 18:52:23.690 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'pipe.rule' doesn't exist
2017-07-07 18:52:23.691 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table rule drop foreign key FKtria2gmd5ghsirwucl003p935
2017-07-07 18:52:23.691 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'pipe.rule' doesn't exist
2017-07-07 18:52:23.693 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table rule drop foreign key FKsoy6c2wf2ahd7y2awnfabuxkc
2017-07-07 18:52:23.694 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'pipe.rule' doesn't exist
2017-07-07 18:52:23.695 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table user drop foreign key FKn82ha3ccdebhokx3a8fgdqeyy
2017-07-07 18:52:23.695 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'pipe.user' doesn't exist
2017-07-07 18:52:24.183  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2017-07-07 18:52:24.238  INFO 11870 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'adminPU'
2017-07-07 18:52:24.300  INFO 11870 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'routerPU'
2017-07-07 18:52:24.301  INFO 11870 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: routerPU
    ...]
2017-07-07 18:52:24.386  INFO 11870 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-07-07 18:52:24.476  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-07 18:52:24.478 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table ip drop foreign key FKnunykfm5kyqpk69fu78rm690t
2017-07-07 18:52:24.478 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'router.ip' doesn't exist
2017-07-07 18:52:24.479 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table ip drop foreign key FK3fkkinqulfhgjo6c7gu8ptu8f
2017-07-07 18:52:24.479 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'router.ip' doesn't exist
2017-07-07 18:52:24.481 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table ip drop foreign key FK4txj00furhr0boqimj1s0loa1
2017-07-07 18:52:24.481 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'router.ip' doesn't exist
2017-07-07 18:52:24.483 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table queue_rule drop foreign key FK5bm4nnopngcrglm6od8m97yhh
2017-07-07 18:52:24.483 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'router.queue_rule' doesn't exist
2017-07-07 18:52:24.485 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table queue_rule drop foreign key FKohmfk4krumgcaa75kxnfxcwfv
2017-07-07 18:52:24.485 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'router.queue_rule' doesn't exist
2017-07-07 18:52:24.486 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table queue_rule drop foreign key FKtc36dnb4iulun0yn72wqrybf4
2017-07-07 18:52:24.486 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'router.queue_rule' doesn't exist
2017-07-07 18:52:24.487 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table queue_rule drop foreign key FK3t8l9ho5h9g7soqrk94h3van0
2017-07-07 18:52:24.487 ERROR 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : Table 'router.queue_rule' doesn't exist
2017-07-07 18:52:25.003  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2017-07-07 18:52:25.007  INFO 11870 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'routerPU'
2017-07-07 18:52:25.124  WARN 11870 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsServiceImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#693f2213' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#693f2213': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2017-07-07 18:52:25.124  INFO 11870 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'routerPU'
2017-07-07 18:52:25.124  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-07 18:52:25.523  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2017-07-07 18:52:25.526  INFO 11870 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'adminPU'
2017-07-07 18:52:25.526  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-07 18:52:25.920  INFO 11870 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2017-07-07 18:52:25.925  WARN 11870 --- [           main] o.s.boot.SpringApplication               : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available)
2017-07-07 18:52:25.985 ERROR 11870 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userRepository in net.elyland.pipe.services.UserDetailsServiceImpl required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

共有1个答案

呼延震博
2023-03-14

请在任何一个数据源配置中的bean上使用@primary注释,它都将起作用。

示例

@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories(
        basePackages = {"net.elyland.pipe.repositories.router"},
        entityManagerFactoryRef = "routerEntityManagerFactory",
        transactionManagerRef = "routerTransactionManager")
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = {"net.elyland.pipe.domain.router"})
public class RouterRepositoryConfiguration {

    @Primary
    @Bean(name = "routerDataSource")
    @ConfigurationProperties(prefix = "router.datasource")
    public DataSource routerDataSource() {
        return DataSourceBuilder
                .create()
                .build();
    }

    @Primary
    @PersistenceContext(unitName = "routerPU")
    @Bean(name = "routerEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean routerEntityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("routerDataSource")DataSource routerDataSource) {
        return builder
                .dataSource(routerDataSource)
                .properties(hibernateProperties())
                .packages(Ip.class, Net.class, Provider.class, QueueRule.class, QueueType.class,RemoteIp.class,Subnet.class,TrafficQueue.class)
                .persistenceUnit("routerPU")
                .build();
    }

    @Primary
    @Bean(name = "routerTransactionManager")
    public PlatformTransactionManager mysqlTransactionManager(@Qualifier("routerEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    private Map hibernateProperties() {

        Resource resource = new ClassPathResource("routerHibernate.properties");

        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);

            return properties.entrySet().stream()
                    .collect(Collectors.toMap(
                            e -> e.getKey().toString(),
                            e -> e.getValue())
                    );
        } catch (IOException e) {
            return new HashMap();
        }
    }
}
 类似资料:
  • 我正在尝试搜索亚马逊的产品广告,并使用botlenose来帮助我做到这一点。但是,我刚刚收到HTTP错误400。 其他一些重要信息: 我来自巴西,我的标签也来自亚马逊。这是个问题吗? 我确实检查了我的钥匙、秘密和标签,一切正常。我确实在StackOverflow上查看了其他一些问题,但对我来说没有任何效果。 当然,出于安全原因,我更改了密钥。 Traceback(最近一次调用最后一次):File"

  • 我有一个基于Spring Web model view controller(MVC)框架的项目。Spring Web模型-视图-控制器(MVC)框架的版本是3.2.8 我有这个控制器 这个URL一切正常:

  • 目前从Angular JS controller中,我试图将JSON数据发送到后端服务。但是我有400个错误的请求错误。 在Controller中,我试图通过http服务发送数据,如下所示:

  • 我得到了这个错误,有什么想法会导致它吗?我试图发送一个DTO,它有一个扩展抽象类的对象列表,我想这个问题可能是因为DTO中的列表,还是因为抽象类的子类?

  • 在月食中, ”org.apache.axis2。AxisFault:传输错误: 403错误:禁止”试图从svn检出项目时发生错误。我不能实现这个错误,因此我检查了从终端使用"svn-co"命令的项目。 但是,有趣的是,当我试图在Eclipse中运行应用程序时,在输入凭据(用户名和密码)并按下“登录”按钮之后,我又遇到了相同的错误。响应是JFrame上的无效用户名/密码,但凭据没有错误。这只发生在日

  • Errors 错误 Library routines must often return some sort of error indication to the caller. As mentioned earlier, Go’s multivalue return makes it easy to return a detailed error description alongside th

  • 本章概述了Google API错误模型,以及开发人员如何正确生成和处理错误的一般指南。 Google API使用简单的协议无关错误模型,这使我们能够在不同的API,API协议(如gRPC或HTTP)以及错误上下文(例如,异步,批处理或工作流错误)中获得一致的体验。 错误模型 错误模型在逻辑上由google.rpc.Status定义,当API发生错误时,返回一个Status实例给客户端。 以下代码段

  • 5.4. 错误 在Go中有一部分函数总是能成功的运行。比如strings.Contains和strconv.FormatBool函数,对各种可能的输入都做了良好的处理,使得运行时几乎不会失败,除非遇到灾难性的、不可预料的情况,比如运行时的内存溢出。导致这种错误的原因很复杂,难以处理,从错误中恢复的可能性也很低。 还有一部分函数只要输入的参数满足一定条件,也能保证运行成功。比如time.Date函数