一、基本环境搭建
1、使用初始化Spring Initializr快速搭建工程
工程创建出来的列表:
在pom文件引入druid依赖
<!--引入druid-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
2、再resource目录下创建application.yml全局配置文件,并做以下参数的配置
application.yml
spring:
datasource:
# 数据源基本配置
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.219.5:3306/mybatis
type: com.alibaba.druid.pool.DruidDataSourceC3P0Adapter
# 数据源其他配置
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,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
接着,需要在navicat客户端工具需要创建一个mybatis的数据库
3、编写数据源的配置类,创建config层DruidConfig类,并做DruidConfig类代码编写
DruidConfig.java
package com.study.springboot.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
chu'c bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
启动主程序,控制台打印出错
所以,在pom文件上,加了一个logger依赖文件
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
启动主程序,控制台,日志文件打印信息:
分析原因:
发现另一个错误,由于自己是连接虚拟机的数据库,而这个错误的原因主要是8080被占用了
解决方案:
方法有两种。
第一种方法:
自定义一个端口号,而自己是自定义一个8084
由于的虚拟机数据库了,需要把以前的服务先停掉,不然发布个应用总不能每次都换端口号,有点麻烦!
所以自己采用第二种方法,就是连接本地的数据库
同样指定一个数据库的端口号8084
全局配置所有的参数:application.yml
server:
port: 8084
spring:
datasource:
# 数据源基本配置
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/mybatis
type: com.alibaba.druid.pool.DruidDataSourceC3P0Adapter
driver-class-name: com.mysql.cj.jdbc.Driver
# 数据源其他配置
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,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
最后,启动主程序启动,控制台日志打印信息:
访问地址:
http://localhost:8084/druid/login.html
这个界面的用户名与密码分别是:
用户名:admin 密码:123456
二、给mybatis数据库创建两张表:
department.sql
/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50528
Source Host : 127.0.0.1:3306
Source Database : restful_crud
Target Server Type : MYSQL
Target Server Version : 50528
File Encoding : 65001
Date: 2018-03-05 10:41:40
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
employee.sql
/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50528
Source Host : 127.0.0.1:3306
Source Database : restful_crud
Target Server Type : MYSQL
Target Server Version : 50528
File Encoding : 65001
Date: 2018-03-05 10:41:58
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` int(2) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
如需要使用springboot项目工程运行,步骤:
1、先把这两个sql文件拷贝到resource目录下创建sql文件下
2、运行sql文件,需要在全局配置文件application.yml配置参数:
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
接着运行主程序
出现错误信息
需要在application.yml加入
?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
url: jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
重新运行主程序
3、封装javabean的实体类
步骤:
首先,创建bean文件,并在该文件下创建Employee类与Department类;
Employee.java
package com.study.springboot.bean;
public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;
public void setId(Integer id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public void setEmail(String email) {
this.email = email;
}
public void setdId(Integer dId) {
this.dId = dId;
}
public Integer getId() {
return id;
}
public String getLastName() {
return lastName;
}
public Integer getGender() {
return gender;
}
public String getEmail() {
return email;
}
public Integer getdId() {
return dId;
}
}
Department.java
package com.study.springboot.bean;
public class Department {
private Integer id;
private String departmentName;
public void setId(Integer id) {
this.id = id;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public Integer getId() {
return id;
}
public String getDepartmentName() {
return departmentName;
}
}
注意:我们需要把全局配置文件的参数注释掉,防止启动再次创建!
4、创建mapper操作数据库(注解版)
步骤:
a、创建mapper文件,并在该文件下DepartmentMapper接口
DepartmentMapper.java
package com.study.springboot.mapper;
import com.study.springboot.bean.Department;
import org.apache.ibatis.annotations.*;
//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
b、创建controller层,并在该文件下创建DeptController类
DeptController.java
package com.study.springboot.controller;
import com.study.springboot.bean.Department;
import com.study.springboot.bean.Employee;
import com.study.springboot.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
}
运行主程序,日志打印信息
访问接口地址
插入数据:http://localhost:8081/deptdepartmentName=张三
数据库刷新后:
自增主键只需要在Mapper层的DepartmentMapper接口类加上一个注解即可
@Options(useGeneratedKeys = true,keyProperty = "id")
效果是:
查询数据:
http://localhost:8081/dept/2
还有另一种方式:
自动配置,也是可以把数据查询出来
MyBatisConfig.java
package com.study.springboot.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
启动时,我们可以把这个@Mapper注解注释掉
再重新启动,日志打印无报错信息
访问接口地址:
查询数据:http://localhost:8081/dept/3
这种操作也是可以查询出来!