4

I want to use two databases with Spring Boot. Here the code:

first db config

@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();
        }
    }
}

Second db config:

@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();
        }
    }
}

Repository 1:

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

Repository 2:

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

properties file:

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

hibernate.properties:

#spring.jpa.show-sql = true
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=create-drop

At the start I have this error:

***************************
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.

Here the full log:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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.

Can somebody say what's wrong? Thanks.

5
  • Spring Boot makes it easier than whatever it is you are trying to do in your code above. Take a look here for the basics on dealing with multiple data sources: stackoverflow.com/questions/30337582/…. Combine this with one of the Spring Boot tutorials on JPA and throw out what you currently have. Commented Jul 7, 2017 at 17:52
  • 1
    Thanks for reply, I changed my code but have the same error. I have tried different configurations but always have had the same error "...required a bean named 'entityManagerFactory' that could not be found". Maybe I miss something impotent. Commented Jul 10, 2017 at 8:43
  • I have tried this config - github.com/manish-in-java/spring-boot-transaction and this example - baeldung.com/spring-data-jpa-multiple-databases and have the same error. If I use one db all works fine. I have spent already one week trying to work it whit no result. Please help. Commented Jul 10, 2017 at 8:55
  • I cant understand, why my app cant autowire right entitymanager if I defined it in config as entityManagerFactoryRef transactionManagerRef Commented Jul 10, 2017 at 9:03
  • Finally, I don't know why but it's working with current configuration github.com/manish-in-java/spring-boot-transaction Commented Jul 10, 2017 at 13:03

2 Answers 2

3

Please use @Primary annotation over the beans in either of the datasource configuration and it will work.

Example:

@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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @flyrock for your answer! Can you explain why is necessary add the '@Primary' annotation in every bean? I got confused. I was confused because my understanding was that '@Primary' annotation is necessary just in the EntityManagerFactoryBean.
0

When having multiple data sources in spring-boot, use separate class for each data source to for the sake of readability of code as well as to avoid such errors (Consider defining a bean named 'entityManagerFactory' in your configuration.)

In case of single datasource in Application, spring boot would have created a default entityManagerFactory bean for it. But on having multiple data sources we need to define entityManagerFactory & transactionManager explicitly for each of them.

For example, you have to use two data sources in your app ds1 & ds2, create beans like below :

Bean for ds1

@Configuration
@Import(SomePrimaryConfig.class)
@EnableJpaRepositories(
    basePackages = "com.ds1.repos",
    entityManagerFactoryRef = "ds1EMF", 
    transactionManagerRef = "ds1TM")
public class DataSource1 {

@Bean
@ConfigurationProperties("ds1.datasource")
public DataSource ds1DataSource() {
    DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
    // other datasource details to set
    return dataSourceBuilder.build();
}

@Bean
LocalContainerEntityManagerFactoryBean ds1EMF(DataSource ds1DataSource) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(ds1DataSource);      
    entityManagerFactoryBean.setPackagesToScan("com.ds1.models");      
    //entityManagerFactoryBean.setJpaProperties(jpaProperties);
    return entityManagerFactoryBean;
}

@Bean
JpaTransactionManager ds1TM(EntityManagerFactory ds1EMF) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(ds1EMF);
    return transactionManager;
 }
}

Bean for ds2

@Configuration
@Import(SomePrimaryConfig.class)
@EnableJpaRepositories(
    basePackages = "com.ds2.repos",
    entityManagerFactoryRef = "ds2EMF", 
    transactionManagerRef = "ds2TM")
public class DataSource2 {

@Bean
@ConfigurationProperties("ds2.datasource")
public DataSource ds1DataSource() {
    DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
    // other datasource details to set
    return dataSourceBuilder.build();
}

@Bean
LocalContainerEntityManagerFactoryBean ds2EMF(DataSource ds2DataSource) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(ds2DataSource);      
    entityManagerFactoryBean.setPackagesToScan("com.ds2.models");      
    //entityManagerFactoryBean.setJpaProperties(jpaProperties);
    return entityManagerFactoryBean;
}

@Bean
JpaTransactionManager ds2TM(EntityManagerFactory ds2EMF) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(ds2EMF);
    return transactionManager;
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.