SpringBoot数据访问
基础JDBC
1)、在虚拟机docker中开启jdbc,切记端口映射
[root@localhost ~]# docker run -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
9493cb1af8c1657615a49ef0f8bc1d2cf4144fd85b0e2c260839804ca3918b19
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9493cb1af8c1 mysql "docker-entrypoint..." 5 seconds ago Up 4 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp musing_ka
lam
2)、在pom.xml中添加mysql和jdbc的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
3)、在全局配置文件中配置数据源
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.177.129:3306/jdbc?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
4)、在测试类中测试
@Autowired
DataSource dataSource;
@Test
void contextLoads() {
System.out.println(dataSource.getClass());
try {
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

使用.sql文件快速建表
在配置文件中将datasource初始化模式设置为always

方式一:将.sql文件命名为schema-*.sql直接放在resources文件夹下,springboot启动时会自动读取并运行

方式二:将.sql文件放在resources文件夹下,在配置文件中指定文件位置


注意:当执行完成功创建数据库之后,一定要将文件删掉,不然每次启动springboot都会重新创建覆盖数据
配置Druid数据源
Druid是现在最常用的数据源,功能强大
首先在pom.xml中引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
在配置文件中指定数据源类型为DruidDataSource

测试

druid支持在配置文件中进行很多的自定义配置,注意filter中一定要写slf4j,springboot默认使用的是slf4j+logback的组合,使用其他日志会报错
#数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
但是经过断点测试发现,并没有设置成功

这是因为springboot自动配置类并没有这些属性,即使将数据源类型改为了druid,没有的属性也是无法配置的,所以我们需要自己创建一个druid数据源配置类,加入到容器中,springboot就会使用我们自动以的配置类了
@Configuration
public class DruidConfig {
//从配置文件将数据注入到类中,此注解需要导入依赖
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource myDruid() {
return new DruidDataSource();
}
}
使用@ConfigurationProperties需要导入这个依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
测试

Druid自带了非常强大的管理界面,接下来配置管理界面
springboot2.0以上,阿里将配置集成到了配置文件中,不需要再自定义配置类进行数据注入或配置监听器和Servlet,更加方便
首先引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.13</version>
</dependency>
配置文件可以直接配置druid的属性
spring:
datasource:
#数据源基本配置
username: root
password: 123456
url: jdbc:mysql://192.168.177.129:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
initialization-mode: always
type: com.alibaba.druid.pool.DruidDataSource
druid:
#数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
web-stat-filter:
enabled: true #是否启用StatFilter默认值true
url-pattern: /*
exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
session-stat-enable: true
session-stat-max-count: 10
stat-view-servlet:
enabled: true #是否启用StatViewServlet默认值true
url-pattern: /druid/*
reset-enable: true
login-username: admin
login-password: 123123
启动springboot,访问localhost:8080,登录即可进入管理界面

模拟一次查询操作

可以在管理界面中监听到刚才的操作
整合Mybatis
环境搭建
在pom.xml中导入mybatis的启动器
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
创建表并创建对应实体类
schema: #创建完记得注释掉,不然每次启动都会重新创建覆盖原来的
- classpath:department.sql
- classpath:employee.sql

mybatis:
configuration:
map-underscore-to-camel-case: true #开启自动驼峰命名转换
1)、使用注解开发简易Mybatis业务
创建实体类对应的Mapper接口,放在Mapper包下
@Mapper //声明这是一个Mapper类,同时将此类注册到容器中
public interface departmentMapper {
@Select("select * from department where id = #{id}")
department getDep(@Param("id") int id);
@Insert("insert into department(departmentName) values(#{Dname})")
int addDep(@Param("Dname") String departmentName);
@Delete("delete from department where id = #{id}")
int delDep(@Param("id") int id);
}
创建Mapper类对应的Controller类
@Controller
public class depController {
@Autowired //@Mapper注解可以让接口自动装配
departmentMapper mapper;
@ResponseBody
@RequestMapping("/find/{id}")
public department find(@PathVariable("id") int id){
department dep = mapper.getDep(id);
return dep;
}
@ResponseBody
@RequestMapping("/add")
public String add(@RequestParam("Dname") String departmentName){
int i = mapper.addDep(departmentName);
return i + "行受影响";
}
@ResponseBody
@RequestMapping("/delete/{id}")
public String del(@PathVariable("id") int id){
int i = mapper.delDep(id);
return i + "行受影响";
}
}
测试

当实体类过多,也许一个一个写Mapper会很麻烦,此时可以在主配置类上添加@MapperScan注解,扫描指定包,让指定包下的接口视为默认添加了@Mapper注解

2)、使用配置开发Mybatis业务
创建实体类对应的Mapper接口,此时不用注解进行sql语句配置,如果没有在主配置类上添加@MapperScan注解,仍需添加@Mapper注解
public interface employeeMapper {
List<employee> findAllEmp();
int insertEmp(employee emp);
}
在resources文件夹下创建mybatis的配置xml和mapper接口对应的xml

其中mapper的配置xml与mybatis原本的配置方式一致,而mybatis的配置xml可以不写,将配置全部在全局配置文件中配置,也可以写,然后在全区配置文件中引入,二者不能共存,即引入的mybatis的配置文件,就不能在全局配置文件中配置任何mybatis配置文件中的<setting>标签可以配置的东西
在全局配置文件中引入配置

创建实体类对应的controller
@Controller
public class empController {
@Autowired
employeeMapper mapper;
@ResponseBody
@RequestMapping("/findAll")
public List<employee> findAll() {
List<employee> allEmp = mapper.findAllEmp();
return allEmp;
}
@ResponseBody
@RequestMapping("/addEmp")
public String add(employee emp) {
int i = mapper.insertEmp(emp);
return i + "行受到了影响";
}
}
测试
