springboot集成mybatis

springboot集成mybatis

文章目录

  • springboot集成mybatis
  • 前言
  • 一、初始化项目
    • 1.创建项目
    • 2.引入依赖
    • 3.创建实体类
    • 4.修改配置文件
  • 二、使用Mybatis
    • 1.纯注解方式
    • 2.使用xml文件方式
  • 三、使用pagehelper分页


前言

MyBatis 是一个开源、轻量级的数据持久化框架,是 JDBC 和 Hibernate 的替代方案。MyBatis 内部封装了 JDBC,简化了加载驱动、创建连接、创建 statement 等繁杂的过程,开发者只需要关注 SQL 语句本身。

一、初始化项目

1.创建项目

在idea中创建一个项目如图
springboot集成mybatis_第1张图片

2.引入依赖

  <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
            <version>2.5.14version>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.29version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.22version>
        dependency>
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelper-spring-boot-starterartifactId>
            <version>1.4.6version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.83version>
        dependency>
    dependencies>

3.创建实体类

数据库脚本如下

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES (1, '张三', '123', '男', '北京');
INSERT INTO `tb_user` VALUES (2, '李四', '321', '女', '济南');
INSERT INTO `tb_user` VALUES (3, '王五', 'jkfdsjoa', '女', '上海');
import lombok.Data;

@Data
public class UserPojo {
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String address;
}

4.修改配置文件

server:
  port: 8080
#数据库配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis
    username: root
    password: root
#mybatis配置
mybatis:
  type-aliases-package: com.demo.dao
  mapper-locations: mapper/*.xml
#分页pageHelper
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true

二、使用Mybatis

1.纯注解方式

定义dao或者叫mapper

package com.demo.dao;

import com.demo.pojo.UserPojo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserDao {

    @Select("Select * from tb_user")
    List<UserPojo> findAll();
}

controller层直接调用

import com.demo.dao.UserDao;
import com.demo.pojo.UserPojo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {

    @Resource
    private UserDao userDao;

    @RequestMapping("/")
    public void findAll(){
        List<UserPojo> all = userDao.findAll();
        all.forEach(item->{
            System.out.println(item);
        });
    }
}

结果如下
在这里插入图片描述

2.使用xml文件方式

在/resources下创建mapper文件夹里边存放所有的mapper.xml文件
在mapper文件夹下创建UserMapper.xml

namespace:是对应数据操作层的路径地址
id:方法名
resultType:返回结果类的地址

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.demo.dao.UserDao">
    <select id="findAllUser" resultType="com.demo.pojo.UserPojo">
        select * from tb_user
    </select>
</mapper>

在UserDao中新增一个接口

    List<UserPojo> findAllUser();

在controller中新增一个findAllUser接口

    @RequestMapping("/user")
    public void findAllUser(){
        List<UserPojo> all = userDao.findAllUser();
        all.forEach(item->{
            System.out.println(item);
        });
    }

结果同上

三、使用pagehelper分页

创建service层

package com.demo.service;

import com.demo.pojo.UserPojo;
import com.github.pagehelper.PageInfo;

public interface UserService {

    PageInfo<UserPojo> pageUser(int pageNumber,int pageSize);
}

package com.demo.service.impl;

import com.demo.dao.UserDao;
import com.demo.pojo.UserPojo;
import com.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public PageInfo<UserPojo> pageUser(int pageNumber, int pageSize) {
        PageHelper.startPage(pageNumber,pageSize);
        //调用dao的查询
        List<UserPojo> list = userDao.findAllUser();
        PageInfo<UserPojo> info = new PageInfo<>(list);
        return info;
    }
}

controller层调用pageUser这个发法

  @RequestMapping("/page")
    public void pageUser(){
        PageInfo<UserPojo> user = userService.pageUser(1, 2);
        System.out.println(JSON.toJSONString(user));
    }

分页成功,结果如下:

{
  "endRow": 2,
  "hasNextPage": true,
  "hasPreviousPage": false,
  "isFirstPage": true,
  "isLastPage": false,
  "list": [
    {
      "address": "北京",
      "gender": "男",
      "id": 1,
      "password": "123",
      "username": "张三"
    },
    {
      "address": "济南",
      "gender": "女",
      "id": 2,
      "password": "321",
      "username": "李四"
    }
  ],
  "navigateFirstPage": 1,
  "navigateLastPage": 2,
  "navigatePages": 8,
  "navigatepageNums": [
    1,
    2
  ],
  "nextPage": 2,
  "pageNum": 1,
  "pageSize": 2,
  "pages": 2,
  "prePage": 0,
  "size": 2,
  "startRow": 1,
  "total": 3
}

你可能感兴趣的:(java,mybatis,spring,boot,java)