官方文档
添加maven依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置
配置数据源相关信息
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
使用
数据表如下
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
1.定义实体类
com.lyp.entity.User
@Data
public class User
{
private Long id;
private String name;
private Integer age;
private String email;
}
2.定义mapper接口
与jpa类似,mybatis提供了默认的CRUD功能,对于简单的单表查询,无需配置mapper映射文件(或者基于注解的sql)。
com.lyp.mapper.UserMapper
@Mapper
public interface UserMapper extends BaseMapper<User>
{
}
3.执行CRUD
com.lyp.controller.MyController
@RestController
public class MyController
{
private final UserMapper userMapper;
@Autowired
public MyController(UserMapper userMapper)
{
this.userMapper = userMapper;
}
@GetMapping("/users")
public Object users()
{
List<User> users = userMapper.selectList(null);
return users;
}
}