mybatis简介

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

springboot集成mybatis,swagger

依赖

  • 引入数据库依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
         <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
  • 引入swagger依赖
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

编写配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/beta?serverTimezon=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: root
mybatis:
  type-aliases-package: hero.mps.l_mybatis.mapper
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: classpsth*:mapper/*.xml

开启服务配置

@SpringBootApplication
@MapperScan("hero.mps.l_mybatis.mapper")
@EnableSwagger2
public class LMybatisApplication {

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

}

集成mybatis实现基本的增删改查

  • 定义user数据库
/*
Navicat MySQL Data Transfer

Source Server         : 127.0.0.1
Source Server Version : 50725
Source Host           : localhost:3306
Source Database       : beta

Target Server Type    : MYSQL
Target Server Version : 50725
File Encoding         : 65001

Date: 2021-04-21 15:15:12
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
  `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
  `user_sex` varchar(32) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('2', '张小敬', '123', 'MAN', 'zxj');
INSERT INTO `users` VALUES ('3', '李司辰', '123', 'MAN', 'lsc');
INSERT INTO `users` VALUES ('4', '崔器', '123', 'MAN', 'cq');
INSERT INTO `users` VALUES ('5', '姚汝能', '123', 'MAN', 'yrn');
INSERT INTO `users` VALUES ('28', '檀棋', '123', ' WOMAN', 'tq');
INSERT INTO `users` VALUES ('29', 'michael', '123', 'MAN', 'zx');
INSERT INTO `users` VALUES ('30', 'MPS', '123456', 'MAN', 'superMa');
INSERT INTO `users` VALUES ('31', 'yq', 'lover', 'WOMAN', 'lover');
INSERT INTO `users` VALUES ('32', 'yq', 'lover', 'WOMAN', 'lover');

id 设置的是自增,当插入数据时,可以不传或者传 null 值,都可以;
插入数据,可以指定 column 也可以不指定;

  • 编写user实体类
@Data
@ApiModel(description = "UserEntity 实体类")
public class UserEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value = "用户 id", dataType = "int")
    private int id;
    @ApiModelProperty(value = "用户名", dataType = "String")
        private String userName;
    @ApiModelProperty(value = "用户密码", dataType = "String")
        private String passWord;
    @ApiModelProperty(value = "用户性别", dataType = "String")
        private String userSex;
    @ApiModelProperty(value = "用户昵称", dataType = "String")
        private String nickName;

    @Override
    public String toString() {
        return "UserEntity{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", userSex='" + userSex + '\'' +
                ", nickName='" + nickName + '\'' +
                '}';
    }
}
  • 编写用户增删改查接口
@Mapper
public interface UserMapper {
    /**
     * 配置驼峰属性自动映射,例如实体中属性为 userSex,数据库属性为 user_sex,MyBatis 默认是不能自动转换的。我们可以配置 mybatis.configuration.map-underscore-to-camel-case 实现自动映射。如果不进行此配置,通常我们要自定义以下结果集映射:
     * @param id
     * @return
     */
    @Results({
            @Result(property = "userSex", column = "user_sex"),
            @Result(property = "nickName", column = "nick_name")
    })
   
    @Select("select * from users where id=#{id}")
    public UserEntity getUserById(@Param("id") int id);
        /**
     * insert 这里用了一个 @Options 的注解,实现了「主键回填」的功能,也就是说,再创建好一个 user 之后,user 请求体中的 id 属性会自动赋值好;
     * @SelectKey 注解被注释掉了,这个注解也同样可以实现「主键回填」的功能;
     * @param user
     */
    @Insert("insert into users(userName, passWord, user_sex, nick_name) values(#{userName}, #{passWord}, #{userSex}, #{nickName})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    public void insertUser(UserEntity user);
       /**
     * 在很多 Select 语句需要做结果映射时,自然是相当麻烦。除了上面配置「驼峰属性自动映射」,也可以用在 @Results 中使用 id 来标识一个映射关系,然后可以用 @ResultMap 复用这个映射关系:
     * @return
     */
    @Select("select * from users")
    public List<UserEntity> getAll();

    @Update("update users set userName=#{userName},nick_name=#{nickName} where id = #{id}")
    void update(UserEntity user);

    @Delete("delete from users where id = #{id}")
    void deleteUserById(int id);

}
  • 编写用户服务业务接口
public interface UserService {
    Map<String, Object> getAll();
    UserEntity getUserById(int id);
    void insertUser(UserEntity userEntity);
    String updateUser(UserEntity userEntity);
    String deleteUserById(int id);
}
  • 用户服务业务接口的实现
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> getAll() {
        List<UserEntity> userEntities = userMapper.getAll();
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", userEntities);
        return map;
    }

    @Override
    public UserEntity getUserById(int id) {
        return userMapper.getUserById(id);
    }

    @Override
    public void insertUser(UserEntity userEntity) {
        userMapper.insertUser(userEntity);
    }

    @Override
    public String updateUser(UserEntity userEntity) {
        userMapper.update(userEntity);
        return "success";
    }

    @Override
    public String deleteUserById(int id) {
        userMapper.deleteUserById(id);
        return "success";
    }
}
  • 编写用户控制类
@RestController
@RequestMapping("/api/v1/")
@Api(tags = {"用户相关接口"}, value = "用户模块")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询全部用户
     * @return
     */
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    @ApiOperation(value = "获取用户列表", notes = "获取全部用户信息")
    public Map<String,Object> getUsers(){
        return userService.getAll();
    }

    /**
     * 根据用户id查询单个用户
     * @param id
     * @return
     */
    @ApiOperation(value = "查询单个用户", notes = "根据用户id查询相关信息")
    @ApiImplicitParam(name = "id", value = "用户id", paramType = "query", required = true)
    @GetMapping("/user/{id}")
    public UserEntity getUserById(@PathVariable("id") int id){
        return userService.getUserById(id);
    }

    /**
     * 存储用户信息
     * @param userEntity
     * @return
     */
    @ApiOperation(value = "存储用户信息", notes = "存储用户详细信息")
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String save(UserEntity userEntity){
        userService.insertUser(userEntity);
        return "create success, user id:" + userEntity.getId();
    }

    /**
     * 更新用户信息
     * @param userEntity
     * @return
     */
    @ApiOperation(value = "更新用户信息", notes = "更新用户个人信息")
    @RequestMapping(value = "/user/",method = RequestMethod.POST)
    public String update(UserEntity userEntity){
        userService.insertUser(userEntity);
        return "create success, user id:" + userEntity.getId();
    }

    /**
     * 根据用户id删除用户
     * @param id
     */
    @ApiOperation(value = "删除用户", notes = "根据用户id删除用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id", required = true,paramType = "path")
    })
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable("id") int id){
        userService.deleteUserById(id);
    }
}
  • 启动服务进行访问