环境
  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用来设置默认数据源  只能配置一个

【Spring Boot学习之三】Spring Boot整合数据源的更多相关文章

  1. Spring Cloud 学习 之 Spring Cloud Eureka(源码分析)

    Spring Cloud 学习 之 Spring Cloud Eureka(源码分析) Spring Boot版本:2.1.4.RELEASE Spring Cloud版本:Greenwich.SR1 ...

  2. Spring Cloud 学习 之 Spring Cloud Eureka(搭建)

    Spring Boot版本:2.1.4.RELEASE Spring Cloud版本:Greenwich.SR1 文章目录 搭建服务注册中心: 注册服务提供者: 高可用注册中心: 搭建服务注册中心: ...

  3. Spring Cloud学习笔记--Spring Boot初次搭建

    1. Spring Boot简介 初次接触Spring的时候,我感觉这是一个很难接触的框架,因为其庞杂的配置文件,我最不喜欢的就是xml文件,这种文件的可读性很不好.所以很久以来我的Spring学习都 ...

  4. Spring Boot学习笔记——Spring Boot与MyBatis的集成(项目示例)

    1.准备数据库环境 # 创建数据库 CREATE DATABASE IF NOT EXISTS zifeiydb DEFAULT CHARSET utf8 COLLATE utf8_general_c ...

  5. [ SSH框架 ] Spring框架学习之三(AOP开发和注解的使用)

    一.Spring 使用 AspectJ 进行 AOP 的开发:注解的方式 1.1 引入相关的jar包 1.2 引入spring的配置文件 <?xml version="1.0" ...

  6. spring cloud学习(六)Spring Cloud Config

    Spring Cloud Config 参考个人项目 参考个人项目 : (希望大家能给个star~) https://github.com/FunriLy/springcloud-study/tree ...

  7. Spring 框架学习(1)--Spring、Spring MVC扫盲

    纸上得来终觉浅,绝知此事要躬行 文章大纲 什么是spring 传统Java web应用架构 更强的Java Web应用架构--MVC框架 Spring--粘合式框架 spring的内涵 spring核 ...

  8. Spring Cloud 学习 (九) Spring Security, OAuth2

    Spring Security Spring Security 是 Spring Resource 社区的一个安全组件.在安全方面,有两个主要的领域,一是"认证",即你是谁:二是& ...

  9. spring深入学习(五)-----spring dao、事务管理

    访问数据库基本是所有java web项目必备的,不论是oracle.mysql,或者是nosql,肯定需要和数据库打交道.一开始学java的时候,肯定是以jdbc为基础,如下: private sta ...

  10. Spring框架学习03——Spring Bean 的详解

    1.Bean 的配置 Spring可以看做一个大型工厂,用于生产和管理Spring容器中的Bean,Spring框架支持XML和Properties两种格式的配置文件,在实际开发中常用XML格式的配置 ...

随机推荐

  1. G6 学习资料

    G6 学习资料 网址 G6 1.x API 文档 http://antvis.github.io/g6/doc/index.html 官方demo列表 https://github.com/antvi ...

  2. Properties 取值和设置函数 Hashtable的静态内部类Entry的结构和克隆方法

  3. 接口调试工具Postman之自动同步Chrome cookies,实现自动登陆验证

    前言 在前后端分离开发时,做为后端开发人员,要求独立开发完成某个接口后,开发人员自己需要先测试通过后再提交给测试人员进行测试,否则会出现到测试人员哪里业务流程根本就走不通,或者BUG会过多的情况等. ...

  4. 分布式session共享

    一.前言 为什么会出现session共享问题? 客户端与服务器交互时会产生唯一的sessionid用于标记用户,但是在分布式架构中,如果还是采用 session 的方式,用户发起请求,通过 nginx ...

  5. 11.06水题Test

    11.06水题比赛 题目 描述 做法 \(BSOJ5150\) 求\(n\)个数两两之差的中位数 二分中位数,双指针判定\(\le x\)差值对数 \(BSOJ5151\) 求树的最大匹配和其个数 来 ...

  6. 洛谷 P1121 环状最大两段子段和 题解

    每日一题 day57 打卡 Analysis 对于这个问题,由于分成了两个子序列,我们不妨就是枚举一下可能出现的情况: 无非就这两种: 1.+++++0000+++++0000++++ 2.0000+ ...

  7. ent 基本使用十九 事务处理

    ent 生成的代码中client 提供了比较全的事务处理 启动单个事务进行处理 // GenTx generates group of entities in a transaction. func ...

  8. CSPS_115

  9. 同余方程组(EXCRT)(luogu4777)

    #include<cstdio> #include<algorithm> #define ll long long using namespace std; ll k; ll ...

  10. 使用adb连接Mumu模拟器

    1)下载Mumu模拟器 2)运行Mumu模拟器 3)找到mumu安装目录下的MuMu\emulator\nemu\vmonitor\bin目录 4)在当前目录打开cmd,执行 adb connect ...