springboot 整合mybaits实现crud操作(含分页)案例

一.操作流程

通过springboot和mybaits整合实现数据的简单crud操作。

另一种方式: springboot+jdbcTemplate的整合实现crud_健康平安的活着的专栏-CSDN博客

常规操作:client的请求-----》controller-----》services-------》dao层----》dao的实现层java类,实现具体的crud操作

此项目的操作:client的请求-----》controller-----》services-------》dao层----》mapper.xml定义了相应crud操作

二.新建项目操作

1.新建项目:springboot-mybaits-demos,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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.ljf.springboot.mybaits.demos</groupId>
  <artifactId>springboot-mybaits-demos</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springboot-mybaits-demos</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <!-- 引入springboot -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--spring boot的依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!--mysql的依赖 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <!--spring boot的依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--  常规依赖 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-joda</artifactId>
      <version>2.9.6</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-parameter-names</artifactId>
    </dependency>
    <!-- 分页插件 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.2.5</version>
    </dependency>
    <!-- alibaba的druid数据库连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.9</version>
    </dependency>



  </dependencies>

  <build>
    <plugins>
      <!--
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      -->
    </plugins>
  </build>
</project>

2.定义model层

package com.ljf.springboot.mybaits.demos.model;

public class UserDomain {
    private int  userId;
    private String userName;
    private String pwd;
    private String tel;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }
}

3.定义dao层

package com.ljf.springboot.mybaits.demos.dao;

import com.ljf.springboot.mybaits.demos.model.UserDomain;

import java.util.List;

public interface UserDao {
    public int addUser(UserDomain ud);
    public List<UserDomain> queryUserList();
}

4.定义mapper:

1.现在工程下创建: resource目录

 2.创建usermapper.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.ljf.springboot.mybaits.demos.dao.UserDao" >
  <sql id="BASE_TABLE">
    tb_user
  </sql>

  <sql id="BASE_COLUMN">
    userId,userName,pwd,tel
  </sql>

  <insert id="addUser" parameterType="com.ljf.springboot.mybaits.demos.model.UserDomain">
    INSERT INTO
      <include refid="BASE_TABLE"/>
    <trim prefix="(" suffix=")" suffixOverrides=",">
      userName,pwd,
      <if test="tel != null">
        tel,
      </if>
    </trim>
    <trim prefix="VALUES(" suffix=")" suffixOverrides=",">
      #{userName, jdbcType=VARCHAR},#{pwd, jdbcType=VARCHAR},
      <if test="tel != null">
        #{tel, jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>


  <select id="queryUserList" resultType="com.ljf.springboot.mybaits.demos.model.UserDomain">
    SELECT
    <include refid="BASE_COLUMN"/>
    FROM
    <include refid="BASE_TABLE"/>
  </select>

</mapper>

5.service层

package com.ljf.springboot.mybaits.demos.services;

import com.github.pagehelper.PageInfo;
import com.ljf.springboot.mybaits.demos.model.UserDomain;

public interface UserService {
    public int addUser(UserDomain ud);

    public PageInfo<UserDomain> queryAllUser(int pageNum, int pageSize);
}

6.serviceimpl实现层:

package com.ljf.springboot.mybaits.demos.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljf.springboot.mybaits.demos.dao.UserDao;
import com.ljf.springboot.mybaits.demos.model.UserDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service(value = "userService")
public class UserServiceImpl implements  UserService {
    @Autowired
    private UserDao userDao;//这里会报错,但是并不会影响
    @Override
    public int addUser(UserDomain ud) {
        return userDao.addUser(ud);
    }

    @Override
    /*
     * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
     * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
     * pageNum 开始页数
     * pageSize 每页显示的数据条数
     * */
    public PageInfo<UserDomain> queryAllUser(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了,非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<UserDomain> userDomains = userDao.queryUserList();
        PageInfo result = new PageInfo(userDomains);
        return result;
    }
}

7.controller层:

package com.ljf.springboot.mybaits.demos.controller;

import com.ljf.springboot.mybaits.demos.model.UserDomain;
import com.ljf.springboot.mybaits.demos.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;


   // @PostMapping("/add")
   @RequestMapping("/add")
   @ResponseBody
    public String addUser(UserDomain user){
        System.out.println("进入controoler........"+user.getUserName());
        int flag=userService.addUser(user);
        System.out.println("controller返回状态........"+flag);
        return "添加成功!!!,返回状态:"+flag+"";

    }
    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
                    int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                    int pageSize){
       System.out.println("进入查询......");
        return userService.queryAllUser(pageNum,pageSize);
    }


}

8.配置启动类:

package com.ljf.springboot.mybaits.demos;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.ljf.springboot.mybaits.demos.dao")
public class StartApp {
    public static void main(String args[]){
        SpringApplication.run(StartApp.class, args);
        System.out.println("服务启动成功!!!!!!!");
        //http://localhost:8080/user/add?userName=ljf&pwd=123&tel=18813010337
    }
}

9.配置application配置文件

server:
  port: 8080
spring:
    datasource:
        name: mysql_test
        type: com.alibaba.druid.pool.DruidDataSource
        #druid相关配置
        druid:
          #监控统计拦截的filters
          filters: stat
          driver-class-name: com.mysql.jdbc.Driver
          #基本属性
          url: jdbc:mysql://127.0.0.1:3306/mytestdb?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
          username: root
          password: root
          #配置初始化大小/最小/最大
          initial-size: 1
          min-idle: 1
          max-active: 20
          #获取连接等待超时时间
          max-wait: 60000
          #间隔多久进行一次检测,检测需要关闭的空闲连接
          time-between-eviction-runs-millis: 60000
          #一个连接在池中最小生存的时间
          min-evictable-idle-time-millis: 300000
          validation-query: SELECT 'x'
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
          #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
          pool-prepared-statements: false
          max-pool-prepared-statement-per-connection-size: 20

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.ljf.springboot.mybaits.demos.model



#pagehelper
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
    returnPageInfo: check

2. spring druid的连接池配置也可以写成

spring:
  datasource:
    # 数据源基本配置
    username: root
    password: cloudiip
    url: jdbc:mysql://127.0.0.1:3306/mytestdb?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
    # driver-class需要注意mysql驱动的版本(com.mysql.cj.jdbc.Driver 或 com.mysql.jdbc.Driver)
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    # Druid的其他属性配置
    druid:
      # 初始化时建立物理连接的个数
      initial-size: 5
      # 连接池的最小空闲数量
      min-idle: 5
      # 连接池最大连接数量
      max-active: 20
      # 获取连接时最大等待时间,单位毫秒
      max-wait: 60000
      # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
      test-while-idle: true
      # 既作为检测的间隔时间又作为testWhileIdel执行的依据
      time-between-eviction-runs-millis: 60000
      # 销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接(配置连接在池中的最小生存时间)
      min-evictable-idle-time-millis: 30000
      # 用来检测数据库连接是否有效的sql 必须是一个查询语句(oracle中为 select 1 from dual)
      validation-query: select 'x'
      # 申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
      test-on-borrow: false
      # 归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
      test-on-return: false
      # 是否缓存preparedStatement, 也就是PSCache,PSCache对支持游标的数据库性能提升巨大,比如说oracle,在mysql下建议关闭。
      pool-prepared-statements: false
      # 置监控统计拦截的filters,去掉后监控界面sql无法统计,stat: 监控统计、Slf4j:日志记录、waLL: 防御sqL注入
      filters: stat,wall,slf4j
      # 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
      max-pool-prepared-statement-per-connection-size: -1
      # 合并多个DruidDataSource的监控数据
      use-global-data-source-stat: true
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

10.新建数据库:

mysql> create database mytestdb;
Query OK, 1 row affected (0.00 sec)

mysql> use mytestdb;
Database changed
mysql> CREATE TABLE tb_user(
    ->   userId INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    ->   userName VARCHAR(255) NOT NULL ,
    ->   pwd VARCHAR(255) NOT NULL ,
    ->   tel VARCHAR(255) NOT NULL
    -> ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.06 sec)

mysql> show tables;
+--------------------+
| Tables_in_mytestdb |
+--------------------+
| tb_user            |
+--------------------+
1 row in set (0.00 sec)

mysql> select * from tb_user;
Empty set (0.01 sec)
 

三.项目的整体结构

四.开始测试

4.1测试新添数据

页面通过get请求:http://localhost:8080/user/add?userName=ljf&pwd=123&tel=18813010337

console控制台的日志:

4.1测4.2 测试查询

控制台信息:

3.mysql数据:

4.分页查询

ok,到此大工搞成!!!!

github地址:https://github.com/jurfliu/springboot-mybaits-demos.git

都看到这里了,就顺手点击左上角的【关注】按钮,点击右上角的小手,给个评论,关注一下,再走呗!☺

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值