SpringBoot整合MyBatis:反正我就是喜欢写SQL

  1. 云栖社区>
  2. 博客>
  3. 正文

SpringBoot整合MyBatis:反正我就是喜欢写SQL

Mr.Elliot 2018-08-02 19:22:00 浏览818
展开阅读全文
img_47ead2d623292fdd5785a44cfe40fbeb.png
mybatis-logo

IDE:IntelliJ IDEA

img_fa68cc5007e36b49fa6a3c2414d00cf5.png
新建SpringBoot项目

img_c6fa589017ee42e869da723dfff261bb.png
创建项目时添加依赖

所有依赖 :如果缺少依赖请自行补齐坐标

<dependencies>
        <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>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <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>
        </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>
img_fb8b6af535a05ae36271e2639d92cad3.png
项目结构

配置文件修改
这里提供两种配置文件的类型(文件性质大同小异)
1.application.properties

server.port=8080

spring.datasource.name=myboot
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.filters=stat
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/a_mydbtest?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=204
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 'x'
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.pool-prepared-statements=false
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20

mybatis.mapper-locations=classpath:Mapper/*.xml
mybatis.type-aliases-package=com.calista.ssm.pojo


pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

2.application.yml

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/testdata?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:cn.sbm.sbm.pojo

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

配置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="cn.sbm.sbm.dao.UserDao" >
  <sql id="BASE_TABLE">
    t_user
  </sql>

  <sql id="BASE_COLUMN">
    userId,userName,password,phone
  </sql>

  <insert id="insert" parameterType="cn.sbm.sbm.pojo.User">
    INSERT INTO
      <include refid="BASE_TABLE"/>
    <trim prefix="(" suffix=")" suffixOverrides=",">
      userName,password,
      <if test="phone != null">
        phone,
      </if>
    </trim>
    <trim prefix="VALUES(" suffix=")" suffixOverrides=",">
      #{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR},
      <if test="phone != null">
        #{phone, jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

  <select id="selectUsers" resultType="cn.sbm.sbm.pojo.User">
      SELECT
        <include refid="BASE_COLUMN"/>
      FROM
        <include refid="BASE_TABLE"/>
  </select>
</mapper>

UserDao

public interface UserDao {
    int insert(User user);
    List<User> selectUsers();
}

UserService:

public interface UserService {

    int addUser(User user);

    PageInfo<User> findAllUser(int pageNum, int pageSize);
}

UserServiceImpl:

@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;//这里会报错,但是并不会影响

    @Override
    public int addUser(User user) {

        return userDao.insert(user);
    }

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

UserController:

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @PostMapping("/add")
    public int addUser(User user){
        return userService.addUser(user);
    }

    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
                    int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                    int pageSize){
        return userService.findAllUser(pageNum,pageSize);
    }
}

测试:

http://localhost:8080/user/all

Json数据:
{
    "total": 2,
    "list": [
        {
            "userId": 1000,
            "userName": "小明同学",
            "password": "123456",
            "phone": "123456"
        },
        {
            "userId": 1001,
            "userName": "小白白",
            "password": "00000",
            "phone": "123456789"
        }
    ],
    "pageNum": 1,
    "pageSize": 10,
    "size": 2,
    "startRow": 1,
    "endRow": 2,
    "pages": 1,
    "prePage": 0,
    "nextPage": 0,
    "isFirstPage": true,
    "isLastPage": true,
    "hasPreviousPage": false,
    "hasNextPage": false,
    "navigatePages": 8,
    "navigatepageNums": [
        1
    ],
    "navigateFirstPage": 1,
    "navigateLastPage": 1,
    "lastPage": 1,
    "firstPage": 1
}

最后 提醒一下 ,一定要记得在启动类中配置Mapper扫描器 @MapperScan

@SpringBootApplication
@MapperScan(value = "com.calista.ssm.dao")
public class SsmApplication {

    public static void main(String[] args) {
        SpringApplication.run(SsmApplication.class, args);
    }
}

网友评论

登录后评论
0/500
评论
Mr.Elliot
+ 关注