配置多个H2内存数据库

时间:2019-07-30 06:34:48

标签: spring spring-boot h2

        Here is my main class

            import java.util.List;
            import java.util.stream.Collectors;
            import java.util.stream.Stream;

            import javax.annotation.PostConstruct;

            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.boot.SpringApplication;
            import org.springframework.boot.autoconfigure.SpringBootApplication;
            //import org.springframework.context.annotation.ComponentScan;
            import org.springframework.web.bind.annotation.GetMapping;
            import org.springframework.web.bind.annotation.RestController;

            import com.example.MultipleDBConnectionEx.book.repository.BookRepository;
            import com.example.MultipleDBConnectionEx.model.book.Book;
            import com.example.MultipleDBConnectionEx.model.user.User;
            import com.example.MultipleDBConnectionEx.user.repository.UserRepository;

            @SpringBootApplication
            @RestController
            //@ComponentScan(basePackages= {"com.example.MultipleDBConnectionEx.*"})
            public class MultipleDbConnectionExApplication {

                @Autowired
                private BookRepository bookRepository;

                @Autowired 
                private UserRepository userRepository;

                @PostConstruct
                public void addData2DB() {
                    userRepository.saveAll(Stream.of(new User(100,"Keerti"),new User(101,"Pavana"))
                            .collect(Collectors.toList()));
                    bookRepository.saveAll(Stream.of(new Book(111,"Core Java"),new Book(112,"SpringBoot"))
                            .collect(Collectors.toList()));

                }

                @GetMapping("/getUsers")
                public List<User> getUsers(){
                    return userRepository.findAll();
                }

                @GetMapping("/getBooks")
                public List<Book> getBooks(){
                    return bookRepository.findAll();
                }


                public static void main(String[] args) {
                    SpringApplication.run(MultipleDbConnectionExApplication.class, args);
                }

            }

        Here is my Model(Book) classes



            import javax.persistence.Entity;
            import javax.persistence.Id;
            import javax.persistence.Table;


            @Entity
            @Table(name="BOOK_TB")
            public class Book {


                @Id
                private int id;
                private String name;

                public Book(int id, String name) {
                    this.id=id;
                    this.name=name;

                }


                public int getId() {
                    return id;
                }
                public void setId(int id) {
                    this.id = id;
                }
                public String getName() {
                    return name;
                }
                public void setName(String name) {
                this.name = name;
                }

            }


        Here is one more Model class(User)



            import javax.persistence.Entity;
            import javax.persistence.Id;
            import javax.persistence.Table;


            @Entity
            @Table(name="USER_TB")
            public class User{

                @Id
                private int id;
                private String userName;
                public User(int id, String userName) {
                    this.id=id;
                    this.userName=userName;

                }

                public int getId() {
                    return id;
                }
                public void setId(int id) {
                    this.id = id;
                }
                public String getUserName() {
                    return userName;
                }
                public void setUserName(String userName) {
                    this.userName = userName;
                }
            }

        Here is my BookRepository and UserRepository classes


            import org.springframework.data.jpa.repository.JpaRepository;
            import org.springframework.stereotype.Repository;

            import com.example.MultipleDBConnectionEx.model.book.Book;

            @Repository
            public interface BookRepository extends JpaRepository<Book,Integer> {

            }



            import org.springframework.data.jpa.repository.JpaRepository;
            import org.springframework.stereotype.Repository;

            import com.example.MultipleDBConnectionEx.model.user.User;

            @Repository
            public interface UserRepository extends JpaRepository<User,Integer>{

            }


        Here is my config Classes

        import java.util.HashMap;
        import java.util.Map;

        import javax.persistence.EntityManagerFactory;
        import javax.sql.DataSource;

        import org.springframework.beans.factory.annotation.Qualifier;
        import org.springframework.boot.context.properties.ConfigurationProperties;
        import org.springframework.boot.jdbc.DataSourceBuilder;
        import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        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;

        @Configuration
        @EnableTransactionManagement
        @EnableJpaRepositories(entityManagerFactoryRef="bookEntityManagerFactory",basePackages= {
                "com.example.MultipleDBConnectionEx.book.repository"},transactionManagerRef="bookTransactionManager")
        public class BookDBConfig {


            @Bean(name="bookDataSource")
            @ConfigurationProperties(prefix="spring.book.datasource")
            public DataSource dataSource() {
                return DataSourceBuilder.create().build();

            }


            @Bean(name="bookEntityManagerFactory")
            public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder,
                    @Qualifier("bookDatasource")DataSource dataSource) {
            Map<String,Object> properties=new HashMap<>();
            properties.put("hibernate.hbm2ddl.auto","update");
            //properties.put("hibernate.hbm2ddl.auto", "update");   
                        return builder.dataSource(dataSource).properties(properties).packages("com.example.MultipleDBConnectionEx.model.book")
                                .persistenceUnit("Book").build();

            }


            @Bean(name = "bookTransactionManager")
            public PlatformTransactionManager transactionManager(
                    @Qualifier("bookEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
                return new JpaTransactionManager(entityManagerFactory);
            }

        }




    import java.util.HashMap;
    import java.util.Map;

    import javax.persistence.EntityManagerFactory;
    import javax.sql.DataSource;

    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    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;

    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(entityManagerFactoryRef="bookEntityManagerFactory",basePackages= {
            "com.example.MultipleDBConnectionEx.book.repository"},transactionManagerRef="bookTransactionManager")
    public class BookDBConfig {


        @Bean(name="bookDataSource")
        @ConfigurationProperties(prefix="spring.book.datasource")
        public DataSource dataSource() {
            return DataSourceBuilder.create().build();

        }


        @Bean(name="bookEntityManagerFactory")
        public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder,
                @Qualifier("bookDatasource")DataSource dataSource) {
        Map<String,Object> properties=new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto","update");
        //properties.put("hibernate.hbm2ddl.auto", "update");   
                    return builder.dataSource(dataSource).properties(properties).packages("com.example.MultipleDBConnectionEx.model.book")
                            .persistenceUnit("Book").build();

        }


        @Bean(name = "bookTransactionManager")
        public PlatformTransactionManager transactionManager(
                @Qualifier("bookEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
            return new JpaTransactionManager(entityManagerFactory);
        }

    }



Here is my Pom file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>MultipleDBConnectionEx</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MultipleDBConnectionEx</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--   <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency> -->

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
     <version>5.2.3.Final</version> 
 </dependency> 


<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.7.Final</version>
</dependency>
 <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
 </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

错误消息

2019-07-30 12:03:58.085  INFO 3744 --- [  restartedMain] c.e.M.MultipleDbConnectionExApplication  : Starting MultipleDbConnectionExApplication on WKSBAN29RBW1176 with PID 3744 (started by keerti.x in C:\Users\keerti.x\Downloads\MultipleDBConnectionEx (2)\MultipleDBConnectionEx\MultipleDBConnectionEx)
2019-07-30 12:03:58.085  INFO 3744 --- [  restartedMain] c.e.M.MultipleDbConnectionExApplication  : No active profile set, falling back to default profiles: default
2019-07-30 12:03:58.367  INFO 3744 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-07-30 12:03:58.367  INFO 3744 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-07-30 12:03:59.429  INFO 3744 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-30 12:03:59.554  INFO 3744 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 109ms. Found 1 repository interfaces.
2019-07-30 12:03:59.554  INFO 3744 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-30 12:03:59.585  INFO 3744 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 31ms. Found 1 repository interfaces.
2019-07-30 12:04:00.398  INFO 3744 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$5d40e31b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-30 12:04:01.038  INFO 3744 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-30 12:04:01.083  INFO 3744 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-30 12:04:01.083  INFO 3744 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-30 12:04:01.520  INFO 3744 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-30 12:04:01.520  INFO 3744 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3153 ms
2019-07-30 12:04:01.629  WARN 3744 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookEntityManagerFactory' defined in class path resource [com/example/MultipleDBConnectionEx/book/config/BookDBConfig.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2019-07-30 12:04:01.629  INFO 3744 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-07-30 12:04:01.676  INFO 3744 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-07-30 12:04:02.004 ERROR 3744 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Parameter 0 of method entityManagerFactoryBean in com.example.MultipleDBConnectionEx.book.config.BookDBConfig required a bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' in your configuration.

0 个答案:

没有答案