一、前言
- Mybatis:数据持久化框架
- Mybatis-Plus:对Mybatis进行了增强,它封装了基本的增删改查操作,使我们自己不需要再去写很多重复的代码,大大解放了生产力!
二、创建项目
创建成功后删除src下面的test目录
三、目录结构
四、pom.xml
修改pom.xml内容如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.llh</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>1.0.0</version>
<name>spring-boot-demo</name>
<description>springboot project description</description>
<properties>
<mybatis-spring-boot.version>2.1.4</mybatis-spring-boot.version>
<mybatis-plus.version>3.4.2</mybatis-plus.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
</dependencies>
</project>
说明:
中 spring-boot-starter-parent 帮我们做了SpringBoot相关依赖包的版本号管理,所以有些依赖包不需要我们自己去写
但像 mybatis-plus-boot-starter 它是不属于spring-boot相关的, parent中没有做版本号管理,所以还需要手动写一下。
五、sql和application.properties
5.1 导入sql语句
CREATE TABLE `user_info` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`username` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '用户名' COLLATE 'utf8mb4_general_ci',
`password` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '密码' COLLATE 'utf8mb4_general_ci',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
);
说明:创建一个数据库,然后运行上述sql语句,生成用户表,主要就下面四个字段
- id 用户id 自增主键
- username 用户名
- password 密码
- create_time 创建时间
5.2 修改application.properties配置文件
# 应用名称
spring.application.name=spring-boot-demo
server.port=8888
# 数据库相关
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# mybatis相关
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
说明:
- 数据库地址 localhost:3306/demo, demo就是数据库名称
- 数据库用户名 spring.datasource.username
- 数据库密码 spring.datasource.password
- mybatis.mapper-locations 配置扫码xml文件
六、逻辑代码
SpringBootDemoApplication 类
package com.llh.springbootdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author llh
*/
@SpringBootApplication
@MapperScan(value = "com.llh.springbootdemo.mapper")
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
说明:启动类上加上
@MapperScan(value = "com.llh.springbootdemo.mapper")
作用是扫描到mapper里面中的类,注意路径要和项目中实际路径一致
UserInfo 类
package com.llh.springbootdemo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
/**
* @author llh
*/
public class UserInfo {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String username;
private String password;
private LocalDateTime createTime;
public Long getId() {
return id;
}
public void setId(Long 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;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", createTime=" + createTime +
'}';
}
}
说明:这里类成员变量和数据库字段对应,Mybatis自动做了驼峰法到下划线的转换
如:数据库 create_time -> 类变量 createTime
UserInfoMapper 类
package com.llh.springbootdemo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.llh.springbootdemo.entity.UserInfo;
/**
* @author llh
*/
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
说明:BaseMapper 类封装了dao层基本的增删改查操作
mapper/UserInfoMapper.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="com.llh.springbootdemo.mapper.UserInfoMapper">
</mapper>
说明:这里的namespace和上述的UserInfoMapper路径对应一致
UserInfoService 类
package com.llh.springbootdemo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.llh.springbootdemo.entity.UserInfo;
/**
* @author llh
*/
public interface UserInfoService extends IService<UserInfo> {
}
说明:这里IService封装了service层基本的增删改查
UserInfoServiceImpl 类
package com.llh.springbootdemo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.mapper.UserInfoMapper;
import com.llh.springbootdemo.service.UserInfoService;
import org.springframework.stereotype.Service;
/**
* @author llh
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
}
UserInfoController 类
package com.llh.springbootdemo.controller;
import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.service.UserInfoService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author llh
*/
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
@PostMapping("/add")
public Boolean add(@RequestBody UserInfo userInfo) {
userInfo.setCreateTime(LocalDateTime.now());
return userInfoService.save(userInfo);
}
@GetMapping("/delete/{id}")
public Boolean delete(@PathVariable Long id) {
return userInfoService.removeById(id);
}
@PostMapping("/update")
public Boolean update(@RequestBody UserInfo userInfo) {
return userInfoService.updateById(userInfo);
}
@GetMapping("/get/{id}")
public UserInfo get(@PathVariable Long id) {
return userInfoService.getById(id);
}
@GetMapping("/list")
public List<UserInfo> list() {
return userInfoService.list();
}
}
说明:
- 增删改查接口,基本上不需要自己写sql,直接调用Mybatis-Plus封装好的接口。
七、结语
用Mybatis-Plus是不是很简单,嘿嘿。
简单看一下,Mybatis-Plus增删改查方法接口如下:
Mybatis属于半配置型的数据持久化框架,JPA是直接封装了所有的SQL操作,相对于JPA来说Mybatis更灵活,可以自定义SQL。同时Mybatis-Plus又为你封装了常用的增删改查操作,这样既可以在特殊情况下自定义SQL,又避免了写大量重复的增删改查。
关注微信公众号:“小虎哥的技术博客”。我们会定期发布关于Java技术的详尽文章,让您能够深入了解该领域的各种技巧和方法,让我们一起成为更优秀的程序员👩💻👨💻!