第一步:创建Maven项目

  • 添加Maven依赖
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.21</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.22</version>
    </dependency>

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.0</version>
    </dependency>

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-core</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-extension</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-annotation</artifactId>
        <version>3.3.0</version>
    </dependency>
    <!-- 解决LocalDate问题-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-typehandlers-jsr310</artifactId>
        <version>1.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
  • 编写配置文件application.yml
server:
  port: 80
  servlet:
    context-path: /imbp

spring:
  #配置数据源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
    # 连接池的配置信息:初始化大小,最小,最大
    initial-size: 8
    min-idle: 1
    max-active: 20
    # 配置获取连接等待超时的时间
    max-wait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    time-between-eviction-runs-millis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    min-evictable-idle-time-millis: 300000
    #验证库是否正常sql
    validation-query: select 'x' from dual
    #空闲时验证,防止连接断开
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    # 打开PSCache,并且指定每个连接上PSCache的大小
    pool-prepared-statements: true
    max-open-prepared-statements: 20
    max-pool-prepared-statement-per-connection-size: 20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    use-global-data-source-stat: true


#MyBatisPlus相关配置
mybatis-plus:
  #mapper映射文件位置,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
  mapper-locations: classpath:mapper/*.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.hc.bean
  #  以下配置均有默认值,可以不设置
  global-config:
    db-config:
      #主键类型
      id-type: auto

      table-underline: true

      #逻辑删除配置(下面3个配置)
      logic-delete-value: -1
      logic-not-delete-value: 1
      logic-delete-field: flag

      #数据库大写下划线转换
      capital-mode: true

  configuration:
    # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
    map-underscore-to-camel-case: true

    cache-enabled: false
    #配置JdbcTypeForNull
    jdbc-type-for-null: 'null'
    # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
    call-setters-on-nulls: true
    # 将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

第二步:编写配置文件

  • MyBatisPlusConfig
@Configuration
public class MyBatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

}
  • DruidConfig
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }

    /**
     * druid 数据源状态监控
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        //创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //设置ip白名单
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
        servletRegistrationBean.addInitParameter("deny","192.168.0.19");
        //设置控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername","druid");
        servletRegistrationBean.addInitParameter("loginPassword","1234");
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    /**
     * druid 过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean statFilter(){
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

我们可以通过网页的方式查看Druid监控,有关知识请参考博客:<a rel="nofollow" href="https://blog.csdn.net/lianghecai52171314/article/details/105411113">SpringBoot整合Druid</a>

第三步:编写实体类

@Getter
@Setter
@ToString
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "db_test.tb_emp")
public class Emp implements Serializable {

    private static final long serialVersionUID = -1696472017703928733L;

    @TableId(value = "empno", type = IdType.INPUT)
    private Integer empno;

    @TableField(value = "ename")
    private String ename;

    @TableField(value = "job")
    private String job;

    @TableField(value = "mgr")
    private Integer mgr;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @TableField(value = "hiredate")
    private LocalDate hiredate;

    @TableField(value = "sal")
    private BigDecimal sal;

    @TableField(value = "comm")
    private BigDecimal comm;

    @TableField(value = "deptno")
    private Integer deptno;

}

第四步:编写Dao接口及Mapper文件

  • EmpMapper.java
@Mapper
public interface EmpMapper extends BaseMapper<Emp> {
}
  • EmpMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hc.mapper.EmpMapper">

</mapper>

第五步:编写Service接口及实现类

  • EmpService
public interface EmpService extends IService<Emp>{

}
  • EmpServiceImpl
@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService{

}

第六步:编写Controller

@RestController
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    private EmpService empService;

    @RequestMapping("/getEmpByEmpno")
    public Emp getEmpByEmpno(@RequestParam(value = "empno") Integer empno) {
        Emp res = empService.getById(empno);
        return res;
    }

    @RequestMapping("/listAll")
    public List<Emp> listAll() {
        System.out.println(empService);
        List<Emp> res = empService.list();
        return res;
    }

    @RequestMapping("/listByCondition")
    public List<Emp> listByCondition(String ename, Integer deptno) {

        QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Emp::getEname, ename)
                .eq(Emp::getDeptno, deptno);

        List<Emp> emplist = empService.list(queryWrapper);

        return emplist;
    }

    @RequestMapping("/page")
    public IPage<Emp> page(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        //需要在Config配置类中配置分页插件
        IPage<Emp> page = new Page<>(pageNum, pageSize);
        IPage<Emp> res = empService.page(page);
        return res;
    }

    //emp/save?empno=1234&ename=zhangsan&job=clerk&mgr=7788&hiredate=1999-09-21&sal=789&deptno=40
    @RequestMapping("/save")
    public boolean save(Emp emp) {
        boolean res = empService.save(emp);
        return res;
    }

    //emp/update?empno=1234&ename=lisi&job=manager&mgr=7788&hiredate=1999-09-21&sal=789&deptno=20
    @RequestMapping("/update")
    public boolean update(Emp emp) {
        boolean res = empService.updateById(emp);
        return res;
    }

    //emp/saveOrUpdate?empno=1234&ename=zhangsan&job=manager&mgr=7788&hiredate=1999-09-21&sal=789&deptno=20
    @RequestMapping("/saveOrUpdate")
    public boolean saveOrUpdate(Emp emp) {
        //实体类ID值存在,如果数据库存在ID就会更新,如果不存在就会新增
        boolean res = empService.saveOrUpdate(emp);
        return res;
    }

    @RequestMapping("/removeById")
    public boolean removeById(Integer id) {
        boolean res = empService.removeById(id);
        return res;
    }

}