Mybatis_Plus
Mybatis 是半ORM框架,需要自己写SQL。 MyBatis-Plus 不需要编写SQL。 官方文档 (opens new window)
本文测试环境
- Spring Boot 2.7.6
- Mybtais Plus Starter 3.5.1
- MySQL 5.7
- MySQL Connector 8.0.16
# 一、安装配置使用
# 1、引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
1
2
3
4
5
2
3
4
5
# 2、快速配置
spring:
# 数据库连接配置
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&&useSSL=false
username: root
password: puhou
mybatis-plus:
# 配置MyBatis日志
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 配置表前缀
table-prefix: t_
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 3、快速开始
MainRunner
@SpringBootApplication
// 指定Mapper存放位置,Mybatis Plus 会扫描这个包下被 @Mapper 标记的接口,为其生成实际操作。
@MapperScan("io.github.human0722.demo.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
domain.User
class User {
private String id;
private String name;
}
1
2
3
4
2
3
4
mapper.UserMapper
public interface UserMapper extends BaseMapper<User> {
}
1
2
3
2
3
test.UserMapperTest
@SprintBootTest
class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void test() {
//userMapper.xxx()
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
通用Service的方式
public interface UserService extends IService<User> {
}
/**
* ServiceImpl 实现了 IService,提供了基础功能。也可自定义添加额外的功能。
*/
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 常用注解
# @TableName
标注在类上,将实体类与数据表绑定。 @Table("t_user)
表示将类与表 t_user
绑定。如果没有这个注解,会默认根据类名生成表名。
Class User{}
与表 user
绑定, Class UserInfo{}
与 user_info
绑定。
# @TableId
标注在属性上,表示这个属性对应数据表的主键, 可以通过 value 值指定主键生成策略。 如果没有属性被注解,那么将自动选择 id 作为主键且使用雪花算法生成。
@TableId(IdType.Auto)
配置数据库 auto increment 属性使用,表示递增。TableId(IdType.ASSIGN_ID)
默认策略,雪花算法。
# @TableField
标注在属性上,将属性与数据表列绑定。
# @TableLogic
标记为逻辑删除字段,标记后所有的删除都是假删除。