• 【Spring Boot学习之三】Spring Boot整合数据源


    环境
      eclipse 4.7
      jdk 1.8
      Spring Boot 1.5.2

    一、Spring Boot整合Spring JDBC

    1、pom.xml

    <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>
        <groupId>com.wjy</groupId>
        <artifactId>springboot-helloworld</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.2.RELEASE</version>
        </parent>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-freemarker</artifactId>
            </dependency>
            <!-- jdbc模板-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency> 
            <!-- mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
        </dependencies>
        
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    2、controller

    package com.wjy.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.wjy.service.UserService;
    
    
    @RestController
    public class UserController {
    
        @Autowired
        public UserService userService;
        
        
        @RequestMapping("/createUser")
        public String createUser(String name, Integer age) {
            userService.createUser(name, age);
            return "success";
        }
    
    }

    3、service

    package com.wjy.service;
    
    public interface UserService {
        
        public String createUser(String username,Integer age) ;
    
    }

    impl:

    package com.wjy.service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Service;
    
    import com.wjy.service.UserService;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
        public String createUser(String username,Integer age) {
            jdbcTemplate.update("insert into users values(null,?,?)",username,age);
            return "success";
        }
        
        
    }

    4、APP.java

    @EnableAutoConfiguration
    @ComponentScan(basePackages= {"com.wjy.controller","com.wjy.service"})
    public class App {
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    
    }

    5、测试验证:  http://localhost:8080/createUser?name=wangjunyu&age=20

    问题:

    1、报错:

    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
    No qualifying bean of type [JdbcTemplate] found for dependency: 
    expected at least 1 bean which qualifies as autowire candidate for this dependency. 
    Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    报错原因:spring boot整合jdbc  至少需要spring-boot-starter-parent 1.5以上.

    2、告警:

    Wed Jul 17 12:47:29 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

    是Mysql数据库的SSL连接问题,提示警告不建议使用没有带服务器身份验证的SSL连接,是在MYSQL5.5.45+, 5.6.26+ and 5.7.6+版本中才有的这个问题。解决办法在警告中已经说明了:

    (1) 在数据库连接的url中添加useSSL=false;
    (2) url中添加useSSL=true,并且提供服务器的验证证书。如果只是做一个测试的话,没必要搞证书那么麻烦啦,在连接后添加一个useSSL=false即可

    二、Spring Boot整合Spring JPA
    Spring JPA是对Hibernate的封装

    1、pom.xml

    <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>
        <groupId>com.wjy</groupId>
        <artifactId>springboot-helloworld</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.2.RELEASE</version>
        </parent>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-freemarker</artifactId>
            </dependency> 
            <!-- JPA模板-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <!-- mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
        </dependencies>
        
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    2、controller

    package com.wjy.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.wjy.dao.UserDao;
    import com.wjy.entity.User;
    
    
    @RestController
    public class UserController {
    
    
        @Autowired
        public UserDao userDao;
    
        
        @RequestMapping("/getUser")
        public User getUser(Integer id) {
            return userDao.findOne(id);
        }
        
    }

    3、Dao

    package com.wjy.dao;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import com.wjy.entity.User;
    
    public interface UserDao extends JpaRepository<User,Integer>{
    
    }

    4、APP

    package com.wjy.app;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.domain.EntityScan;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    
    @EnableAutoConfiguration
    @ComponentScan(basePackages= {"com.wjy.controller"})
    @EnableJpaRepositories("com.wjy.dao")
    @EntityScan("com.wjy.entity")
    public class App {
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    
    }

    5、测试验证  http://localhost:8080/getUser?id=1

    三、Spring Boot整合Mybatis
    Mybatis两个版本:注解版本和XML配置版本

    这里展示注解版:

    1、pom.xml

    <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>
        <groupId>com.wjy</groupId>
        <artifactId>springboot-helloworld</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.2.RELEASE</version>
        </parent>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-freemarker</artifactId>
            </dependency>
            
            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version>
            </dependency>
            
            <!-- mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
        </dependencies>
        
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    2、controller

    package com.wjy.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.wjy.entity.User;
    import com.wjy.mapper.UserMapper;
    
    @RestController
    public class UserController {
        
        @Autowired
        public UserMapper userMapper;
        
        @RequestMapping("/findByname")
        public User findByname(String name) {
            return userMapper.findByName(name);
        }
        
    }

    3、mapper

    package com.wjy.mapper;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import com.wjy.entity.User;
    
    
    public interface UserMapper {
        @Select("SELECT * FROM USERS WHERE NAME = #{name}")
        User findByName(@Param("name") String name);
    
        @Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
        int insert(@Param("name") String name, @Param("age") Integer age);
    }

    4、APP

    package com.wjy.app;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.domain.EntityScan;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    
    @EnableAutoConfiguration
    @ComponentScan(basePackages= {"com.wjy.controller"})
    @MapperScan("com.wjy.mapper")
    public class App {
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    
    }

    5、测试验证 http://localhost:8080/findByname?name=wangjunyu

     四、Spring Boot整合多数据源

     有两种方式:

    (1)分包方式:文件分包,这种用的多一些,这里只介绍这种方式;

    (2)注解方式:这种会繁琐一些,每创建一个方法就需要加注解;

    1、数据源配置

    #test1
    spring.datasource.test1.url=jdbc:mysql://192.168.118.102:3306/springboot?useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf-8
    spring.datasource.test1.username=root
    spring.datasource.test1.password=123456
    spring.datasource.test1.driver-class-name=com.mysql.jdbc.Driver
    
    #test2
    spring.datasource.test2.url=jdbc:mysql://192.168.118.102:3306/springboot2?useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf-8
    spring.datasource.test2.username=root
    spring.datasource.test2.password=123456
    spring.datasource.test2.driver-class-name=com.mysql.jdbc.Driver

    2、创建数据源

    package com.wjy.datasource;
    
    import javax.sql.DataSource;
    
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    
    //注册到springboot容器中
    @Configuration  
    //@MapperScan可以指定要扫描的Mapper类的包的路径  sqlSessionFactoryRef 表示定义了 key ,表示一个唯一 SqlSessionFactory 实例
    @MapperScan(basePackages="com.wjy.test1",sqlSessionFactoryRef="sqlSessionFactory1")
    public class DataSource1Config {
        
        /**
         * @Description: 配置test1数据库
         * @author wangjy15
         * @date 2019年7月22日 下午2:19:18 
         * @return 
         */
        @Bean(name="dataSource1")
        @ConfigurationProperties(prefix="spring.datasource.test1")
        @Primary   //默认数据源
        public DataSource dataSource1() {
            return DataSourceBuilder.create().build();
        }
    
        /**
         * @Description: test1 sql会话工厂 
         * @author wangjy15
         * @date 2019年7月22日 下午2:28:01 
         * @param dataSource
         * @return
         * @throws Exception 
         */
        @Bean(name="sqlSessionFactory1")
        @Primary
        public SqlSessionFactory sqlSessionFactory1(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            //mybatis写配置文件
            //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
            return bean.getObject();
        }
        
        /**
         * @Description: test1 事务管理 
         * @author wangjy15
         * @date 2019年7月22日 下午2:30:50 
         * @param dataSource
         * @return 
         */
        @Bean(name="transactionManager1")
        @Primary
        public DataSourceTransactionManager transactionManager1(@Qualifier("dataSource1") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
        
        /**
         * @Description: SqlSessionTemplate 
         * @author wangjy15
         * @date 2019年7月22日 下午2:34:24 
         * @param sqlSessionFactory
         * @return 
         */
        @Bean(name="sqlSessionTemplate1")
        @Primary
        public SqlSessionTemplate sqlSessionTemplate1(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
        
    }
    package com.wjy.datasource;
    
    import javax.sql.DataSource;
    
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    
    //注册到springboot容器中
    @Configuration  
    //@MapperScan可以指定要扫描的Mapper类的包的路径  sqlSessionFactoryRef 表示定义了 key ,表示一个唯一 SqlSessionFactory 实例
    @MapperScan(basePackages="com.wjy.test2",sqlSessionFactoryRef="sqlSessionFactory2")
    public class DataSource2Config {
    
        /**
         * @Description: 配置test2数据库
         * @author wangjy15
         * @date 2019年7月22日 下午2:19:18 
         * @return 
         */
        @Bean(name="dataSource2")
        @ConfigurationProperties(prefix="spring.datasource.test2")
        public DataSource dataSource2() {
            return DataSourceBuilder.create().build();
        }
    
        /**
         * @Description: test2 sql会话工厂 
         * @author wangjy15
         * @date 2019年7月22日 下午2:28:01 
         * @param dataSource
         * @return
         * @throws Exception 
         */
        @Bean(name="sqlSessionFactory2")
        public SqlSessionFactory sqlSessionFactory2(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            //mybatis写配置文件
            //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
            return bean.getObject();
        }
        
        /**
         * @Description: test2 事务管理 
         * @author wangjy15
         * @date 2019年7月22日 下午2:30:50 
         * @param dataSource
         * @return 
         */
        @Bean(name="transactionManager2")
        public DataSourceTransactionManager transactionManager2(@Qualifier("dataSource2") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
        
        /**
         * @Description: SqlSessionTemplate 
         * @author wangjy15
         * @date 2019年7月22日 下午2:34:24 
         * @param sqlSessionFactory
         * @return 
         */
        @Bean(name="sqlSessionTemplate2")
        public SqlSessionTemplate sqlSessionTemplate2(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

    3、mapper

    /**
     * 
     */
    package com.wjy.test1.dao;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import com.wjy.entity.User;
    
    /**
     * @Desc
     * @author wangjy15
     */
    public interface UserMapperTest1 {
        
        @Select("SELECT * FROM users WHERE NAME = #{name}")
        User findByName(@Param("name") String name);
    
        @Insert("insert into users (name,age) values(#{name},#{age})")
        int insert(@Param("name") String name,@Param("age") Integer age);
    }
    /**
     * 
     */
    package com.wjy.test2.dao;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import com.wjy.entity.User;
    
    /**
     * @Desc
     * @author wangjy15
     */
    public interface UserMapperTest2 {
        
        @Select("SELECT * FROM users WHERE NAME = #{name}")
        User findByName(@Param("name") String name);
        
        @Insert("insert into users (name,age) values (#{name},#{age})")
        int insert(@Param("name") String name,@Param("age") Integer age);
    }

    4、controller

    package com.wjy.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.wjy.test1.dao.UserMapperTest1;
    import com.wjy.test2.dao.UserMapperTest2;
    
    @RestController
    public class UserController {
    
        
        @Autowired
        public UserMapperTest1 userMapperTest1;
        
        @Autowired
        public UserMapperTest2 userMapperTest2;
        
        
        @RequestMapping("/insertTest1")
        public String insertTest1(String name,Integer age) {
            userMapperTest1.insert(name, age);
            return "success";
        }
        
        @RequestMapping("/insertTest2")
        public String insertTest2(String name,Integer age) {
            userMapperTest2.insert(name, age);
            return "success";
        }
        
    }

    5、APP

    package com.wjy;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class APP {
    
        public static void main(String[] args) {
            SpringApplication.run(APP.class, args);
        }
    
    }

    6、测试验证

    http://localhost:8080/insertTest1?name=user001&age=11

    http://localhost:8080/insertTest2?name=user002&age=22

    问题:No qualifying bean of type 'javax.sql.DataSource' available: more than one 'primary' bean found among candidates: [dataSource1, dataSource2]

    原因:两个DataSourceConfig类里面都配置了@Primary注解   这样做是错误的  @Primary用来设置默认数据源  只能配置一个

  • 相关阅读:
    李开复给中国学生的第一封信
    vc++学习篇(三)——预处理命令之条件编译(#ifdef,#else,#endif,#if等)
    高级程序员考试时间安排和参考书推荐
    vc++学习篇(四)—— 指针
    程序员应具备的素质
    Word 2003 长篇文档排版技巧(二)
    Google 技巧集锦
    给中国学生的第二封信
    修复mysql表
    社保相关
  • 原文地址:https://www.cnblogs.com/cac2020/p/11224642.html
Copyright © 2020-2023  润新知