Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。本文将介绍在springboot中使用mybatisplus。
1、前提约束
- 在mysql数据库中的test数据库实例下有一张表user,初始化语句如下:
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id INT(20) NOT NULL,
name VARCHAR(30) ,
age INT(11),
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age) VALUES
(1, 'ali', 18),
(2, 'xiaoli', 20),
(3, 'zhangli', 28),
(4, 'xiaoni', 21),
(5, 'zhang', 24);
2、操作步骤
- 完成springboot创建web项目 https://www.jianshu.com/p/de979f53ad80
注意,作者使用的springboot版本是2.2.6.RELEASE - 加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
- 配置application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: zhangli
logging:
level:
net.wanho: DEBUG
server:
port: 8088
- 在主启动类统计目录下创建User.java
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private Integer age;
}
- 在主启动类同级目录下创建UserMapper.java接口
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
@Repository
public interface UserMapper extends Mapper<User> {
}
- 在主启动类同级目录下创建UserController.java
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class UserController {
@Resource
private UserMapper userMapper;
@GetMapping("/list")
public List<User> list() {
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
criteria.andLike("name","%li%");
criteria.andBetween("age",2,20);
List<User> list = userMapper.selectByExample(example);
return list;
}
@GetMapping("/page")
public PageInfo<User> page() {
PageHelper.startPage(1, 2);
List<User> list = userMapper.selectAll();
PageInfo<User> pageInfo = new PageInfo<>(list);
return pageInfo;
}
}
- 在主启动类上面加入Mapper扫描
@MapperScan("net.wanho")//注意,请读者根据自己的实际情况设置扫描路径
以上就是在springboot中使用mybatisplus的过程。
网友评论