SpringBoot整合MyBatis-Plus以及逆向工程

一、快速开始

1.1 官方文档

Mybatis-Plus官方文档链接

1.2 创建数据库和数据库表
/*
 Navicat Premium Data Transfer

 Source Server         : ahao
 Source Server Type    : MySQL
 Source Server Version : 50734
 Source Host           : localhost:3306
 Source Schema         : mp

 Target Server Type    : MySQL
 Target Server Version : 50734
 File Encoding         : 65001

 Date: 10/05/2022 20:26:40
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `money` double NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, '张三', 1600);
INSERT INTO `account` VALUES (2, '李四', 1300);

-- ----------------------------
-- Table structure for author
-- ----------------------------
DROP TABLE IF EXISTS `author`;
CREATE TABLE `author`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `author_name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of author
-- ----------------------------
INSERT INTO `author` VALUES (1, '阿豪', 18);

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bookName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `publishDate` date NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1, '西游记', '2022-04-26');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `password` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `gender` int(2) NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `hobby` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'ahao', '123', 1, 2342, '篮球;敲代码;', '南宁');
INSERT INTO `user` VALUES (5, '达摩', '666', 1, 23, '足球;乒乓球;', '南宁');
INSERT INTO `user` VALUES (6, 'fgdg', '123', 1, 23, '足球;乒乓球;', '南宁');
INSERT INTO `user` VALUES (8, 'zhangsan', '123', 1, 19, '打球', '广西');

SET FOREIGN_KEY_CHECKS = 1;

1.3 创建SpringBoot工程

创建的时候需要勾选 SpringWeb、MyBatisFrameWork、MySQLDrive

  1. 导入mybatis-plus相关依赖
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.1version>
        dependency>

        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-generatorartifactId>
            <version>3.5.2version>
        dependency>
        
        
        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.31version>
        dependency>
  1. 代码生成配置(可以在测试类中运行)
FastAutoGenerator.create("jdbc:mysql:///mp?serverTimezone=Asia/Shanghai&useSSL=false", "root", "123456")
                .globalConfig(builder -> {
                    builder.author("ahao") // 设置作者
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("E:\\GZ-2201\\third\\springboot\\SpringBootProject\\mpdemo\\src\\main\\java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.qfedu.mpdemo") // 设置父包名
        //                    .moduleName("system") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "E:\\GZ-2201\\third\\springboot\\SpringBootProject\\mpdemo\\src\\main\\resources\\mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("account","author","book","user") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

以上代码如果运行成功后,会根据数据库生成相应的entity、service、mapper、controller

  1. 在启动类配置包扫描
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//扫描接口
@MapperScan(basePackages = "com.ahao.mpdemo.mapper")
public class MpdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MpdemoApplication.class, args);
    }

}
  1. 写个Controller试试吧
import com.ahao.mpdemo.entity.Account;
import com.ahao.mpdemo.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
/**
 *这里将查询结果以JSON格式返回浏览器
 *使用的是@RestController
 */
@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    IAccountService accountService;

    @GetMapping("/getAllAccounts")
    public List<Account> getAllAccounts(){
    	//查询所有账户
        return accountService.list();
    }

}

  1. 启动SpringBoot,打开浏览器输入一下地址回车可以看到查询结果SpringBoot整合MyBatis-Plus以及逆向工程_第1张图片
1.4 简单CRUD测试用例
	@Autowired
    IUserService userService;
    @Autowired
    IAccountService accountService;

    @Test
    public void test01(){
    	//添加用户
        User user = new User();
        user.setUsername("法外狂徒");
        user.setAddress("某星球");
        userService.save(user);
    }

    @Test
    public void test02(){
    	//修改
        User user = new User();
        user.setId(9);
        user.setUsername("法外狂徒");
        user.setAddress("某星球");
        userService.saveOrUpdate(user);
    }

    @Test
    public void test03(){
    	//查询用户名以达开头的
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("username", "达");
        List<User> list = userService.list(queryWrapper);
        System.out.println(list);
    }

    @Test
    public void test04(){
    	//查询姓达且位于广州的用户
        QueryWrapper<User>  qw = new QueryWrapper<>();
        qw.likeRight("username","达").eq("address","广州");
        List<User> list = userService.list(qw);
        System.out.println("list = " + list);
    }

    @Test
    public void test05(){
        QueryWrapper<User> qw = new QueryWrapper<>();
        //查询姓达并且位于南宁的用户
        qw.lambda().likeRight(User::getUsername,"达").eq(User::getAddress,"南宁");
        List<User> list = userService.list(qw);
        System.out.println("list = " + list);
    }

    @Test
    public void test06(){
    	//lambda写法,效果同test05
        List<User> list = userService.list(Wrappers.<User>lambdaQuery().likeRight(User::getUsername, "达").eq(User::getAddress, "南宁"));
        System.out.println("list = " + list);
    }

    @Test
    public void test07(){
    	//将所有姓达的用户性别改为男密码改为 123
        boolean update = userService.update(Wrappers.<User>lambdaUpdate().set(User::getGender, 1).set(User::getPassword, "123").likeRight(User::getUsername,"达"));
        System.out.println("update = " + update);
    }

    @Test
    public void test08(){
    	//删除id大于8的用户
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.gt("id",8);
        userService.remove(Wrappers.<User>lambdaQuery().gt(User::getId,8));
    }

    @Test
    public void test09(){
    	//自定义sql
        accountService.update(Wrappers
                .<Account>lambdaUpdate().setSql("money=money+"+1000).eq(Account::getUsername,"张三"));
    }

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