淘先锋技术网

首页 1 2 3 4 5 6 7

目录

一、整合MyBatis

1.先在数据库创建用户表t_user

2.插入表t_user几条测试数据

3.打开pom.xml添加mybatis依赖

4.在study下面新建controller、service、mapper、entity包名,在resources下面新建mapper文件夹,编写相应的代码

5.在SpringBootStudyApplication添加注解@MapperScan扫描Mapper

6.打开application.xml,增加mybatis映射文件xml路径

7.打开类SpringBootStudyApplication,右键运行

8.打开postman测试工具

二、升级为MyBatisPlus

1.打开pom.xml添加mybatis plus依赖

2.打开application.xml,隐藏mybatis映射文件xml路径

3.打开SpringBootStudyApplicationTests编写单元测试,实现代码快速生成.运行单元测试用例,找到代码生成的位子,分别粘贴到相应位子

4.新建config包,增加分布配置类

5.在UserController新建方法用于测试

6.编写业务接口和业务实现层

7.编写数据处理层

8.用调试工具访问


一、整合MyBatis

1.先在数据库创建用户表t_user

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `password` varchar(200) NOT NULL COMMENT '密码',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2.插入表t_user几条测试数据

INSERT INTO `springboot_study`.`t_user` (`username`, `password`) VALUES ('小蓝', '123456');
INSERT INTO `springboot_study`.`t_user` (`username`, `password`) VALUES ('小红', '666666');
INSERT INTO `springboot_study`.`t_user` (`username`, `password`) VALUES ('小紫', '111111');

3.打开pom.xml添加mybatis依赖

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.2.2</version>
</dependency>

4.在study下面新建controllerservicemapperentity包名,在resources下面新建mapper文件夹,编写相应的代码

entity层
package com.saas.springboot.study.entity.dto;

/**
 * 用户查询参数实体类
 */
public class UserDTO {

    /**
     * 主键id
     */
    Integer id;
    /**
     * 用户名
     */
    String username;
    /**
     * 密码
     */
    String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
package com.saas.springboot.study.entity.dto;

/**
 * 用户保存参数实体类
 */
public class UserSaveDTO {

    /**
     * 主键id
     */
    Integer id;
    /**
     * 用户名
     */
    String username;
    /**
     * 密码
     */
    String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
package com.saas.springboot.study.entity.po;

/**
 * 用户表
 */
public class User {

    /**
     * 主键id
     */
    Integer id;
    /**
     * 用户名
     */
    String username;
    /**
     * 密码
     */
    String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
package com.saas.springboot.study.entity.vo;

/**
 * 用户表
 */
public class UserVO {

    /**
     * 主键id
     */
    Integer id;
    /**
     * 用户名
     */
    String username;
    /**
     * 密码
     */
    String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

controller层

package com.saas.springboot.study.controller;

import com.saas.springboot.study.entity.dto.UserSaveDTO;
import com.saas.springboot.study.entity.vo.UserVO;
import com.saas.springboot.study.service.UserService;
import org.springframework.web.bind.annotation.*;

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

@RestController
public class UserController {

    @Resource
    private UserService userService;

    //获取所有的用户信息
    @GetMapping("/getUserInfoList")
    public List<UserVO> getUserInfoList(){
        return userService.getUserInfoList();
    }

    //根据id获取用户信息
    @GetMapping("/getUserInfo")
    public UserVO getUserInfo(@RequestParam("id") Integer id){
        return userService.getUserInfo(id);
    }

    //保存用户信息
    @PostMapping("/saveUserInfo")
    public void saveUserInfo(@RequestBody UserSaveDTO userSaveDTO){
        userService.saveUserInfo(userSaveDTO);
    }
}
service层
package com.saas.springboot.study.service;

import com.saas.springboot.study.entity.dto.UserSaveDTO;
import com.saas.springboot.study.entity.vo.UserVO;

import java.util.List;

public interface UserService {

    List<UserVO> getUserInfoList();

    UserVO getUserInfo(Integer id);

    void saveUserInfo(UserSaveDTO userSaveDTO);

}
package com.saas.springboot.study.service.impl;

import com.saas.springboot.study.entity.dto.UserSaveDTO;
import com.saas.springboot.study.entity.vo.UserVO;
import com.saas.springboot.study.mapper.UserMapper;
import com.saas.springboot.study.service.UserService;
import org.springframework.stereotype.Service;

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

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<UserVO> getUserInfoList() {
        return userMapper.getUserInfoList();
    }

    @Override
    public UserVO getUserInfo(Integer id) {
        return userMapper.getUserInfo(id);
    }

    @Override
    public void saveUserInfo(UserSaveDTO userSaveDTO) {
        userMapper.saveUserInfo(userSaveDTO);
    }
}
mapper层
package com.saas.springboot.study.mapper;

import com.saas.springboot.study.entity.dto.UserSaveDTO;
import com.saas.springboot.study.entity.vo.UserVO;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {

    List<UserVO> getUserInfoList();

    UserVO getUserInfo(@Param("id") Integer id);

    void saveUserInfo(UserSaveDTO userSaveDTO);

}

mapper对应的xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 指明当前xml对应的Mapper -->
<mapper namespace="com.saas.springboot.study.mapper.UserMapper">

    <select id="getUserInfoList" resultType="com.saas.springboot.study.entity.vo.UserVO">
        select id,username,password from t_user
    </select>

    <select id="getUserInfo" resultType="com.saas.springboot.study.entity.vo.UserVO">
        select id,username,password from t_user where id =#{id}
    </select>

    <insert id="saveUserInfo">
        insert into  t_user(username,password) values (#{username},#{password})
    </insert>

</mapper>

5.在SpringBootStudyApplication添加注解@MapperScan扫描Mapper

@MapperScan({"com.saas.springboot.study.mapper"})

6.打开application.xml,增加mybatis映射文件xml路径

mybatis:
    #配置mapper的指定路径
    mapper-locations: classpath:mapper/*.xml

7.打开类SpringBootStudyApplication,右键运行

8.打开postman测试工具

①.访问http://localhost:8888/getUserInfoList获取所有用户信息

 ②.访问http://localhost:8888/getUserInfo?id=1 获取用户id等于1的用户信息

 ③.访问http://localhost:8888/saveUserInfo 添加一个用户

{

    "username":"小明",

    "password":"888888"

}

 

二、升级为MyBatisPlus

1.打开pom.xml添加mybatis plus依赖

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

<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-generator</artifactId>
   <version>3.5.3</version>
</dependency>

<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <scope>test</scope>
</dependency>

  

2.打开application.xml,隐藏mybatis映射文件xml路径

3.打开SpringBootStudyApplicationTests编写单元测试,实现代码快速生成.运行单元测试用例,找到代码生成的位子,分别粘贴到相应位子

package com.saas.springboot.study;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Collections;

@SpringBootTest
class SpringBootStudyApplicationTests {

	@Test
	void contextLoads() {
	}

	@Test
	void testGenerate() {
		//数据库连接地址、用户名、密码
		String url = "jdbc:mysql://localhost:3306/springboot_study?serverTimezone=Asia/Shanghai&characterEncoding=utf-8&useSSL=false";
		String username = "root";
		String password = "123456";
		FastAutoGenerator.create(url, username, password)
				.globalConfig(builder -> {
					builder.author("yy") // 设置作者
							.enableSwagger() // 开启 swagger 模式
							.fileOverride() // 覆盖已生成文件
							.outputDir("D:\\generateCode"); // 指定输出目录
				})
				.packageConfig(builder -> {
					builder.parent("com.saas.springboot.study") // 设置父包名
							//.moduleName("system") // 设置父包模块名
							.pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\generateCode")); // 设置mapperXml生成路径
				})
				.strategyConfig(builder -> {
					builder
							//.addInclude("t_user") // 设置需要生成的表名
							.addTablePrefix("t_", "c_"); // 设置过滤表前缀
				})
				.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
				.execute();

	}

}

4.新建config包,增加分布配置类

package com.saas.springboot.study.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * mybatis分页配置
 */
@Configuration
public class MybatisConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

5.在UserController新建方法用于测试

package com.saas.springboot.study.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.saas.springboot.study.entity.dto.UserSaveDTO;
import com.saas.springboot.study.entity.po.User;
import com.saas.springboot.study.entity.vo.UserVO;
import com.saas.springboot.study.service.UserService;
import org.springframework.web.bind.annotation.*;

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

@RestController
public class UserController {

    @Resource
    private UserService userService;


    //获取所有的用户信息2
    @GetMapping("/getUserInfoList2")
    public List<User> getUserInfoList2(){
        return userService.getUserInfoList2();
    }

    //分页获取用户信息
    @GetMapping("/getUserInfoByPage")
    public Page<User> getUserInfoByPage(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize){
        return userService.getUserInfoByPage(pageNum,pageSize);
    }

    //自定义分页获取用户信息
    @GetMapping("/getUserInfoByPage2")
    public Page<User> getUserInfoByPage2(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, @RequestParam(value = "username",required = false) String username){
        return userService.getUserInfoByPage2(pageNum,pageSize,username);
    }
}

6.编写业务接口和业务实现层

package com.saas.springboot.study.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.saas.springboot.study.entity.dto.UserSaveDTO;
import com.saas.springboot.study.entity.po.User;
import com.saas.springboot.study.entity.vo.UserVO;

import java.util.List;

public interface UserService {

    List<User> getUserInfoList2();

    Page<User> getUserInfoByPage(Integer pageNum, Integer pageSize);

    Page<User> getUserInfoByPage2(Integer pageNum, Integer pageSize, String username);
}

package com.saas.springboot.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.saas.springboot.study.entity.dto.UserSaveDTO;
import com.saas.springboot.study.entity.po.User;
import com.saas.springboot.study.entity.vo.UserVO;
import com.saas.springboot.study.mapper.UserMapper;
import com.saas.springboot.study.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;


    @Override
    public List<User> getUserInfoList2() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(userQueryWrapper);
        return userList;
    }

    @Override
    public Page<User> getUserInfoByPage(Integer pageNum, Integer pageSize) {
        Page<User> userPage = new Page<>(pageNum,pageSize);
        Page<User> page = userMapper.selectPage(userPage, new QueryWrapper<>());
        return page;
    }

    @Override
    public Page<User> getUserInfoByPage2(Integer pageNum, Integer pageSize, String username) {
        Page<User> userPage = new Page<>(pageNum, pageSize);
        return userMapper.getUserInfoByPage(userPage, username);
    }
}

7.编写数据处理层

package com.saas.springboot.study.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.saas.springboot.study.entity.po.User;
import org.apache.ibatis.annotations.Param;

public interface UserMapper extends BaseMapper<User> {

    Page<User> getUserInfoByPage(@Param("page") Page<User> page,@Param("username") String username);

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 指明当前xml对应的Mapper -->
<mapper namespace="com.saas.springboot.study.mapper.UserMapper">

    <select id="getUserInfoByPage" resultType="com.saas.springboot.study.entity.po.User">
        SELECT id,username,password  from t_user
        <where>
            <if test="username != null and username != ''">
                and username like concat('%', #{username}, '%')
            </if>
        </where>
    </select>

</mapper>

8.用调试工具访问

①.访问http://localhost:8888/getUserInfoList2

 

②.访问 http://localhost:8888/getUserInfoByPage?pageNum=2&pageSize=2

 ③.访问http://localhost:8888/getUserInfoByPage2?pageNum=1&pageSize=2&username=红