MyBatisPlus是MyBatis的增强工具,提供了很多便捷的功能,例如自动生成代码、分页查询、乐观锁、逻辑删除等
安装
你可以使用Maven来安装MyBatisPlus依赖。在你的Maven项目中添加以下依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
配置
数据库连接
在你的application.properties或application.yml文件中添加数据库连接信息:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis_plus_demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
在上述代码中,mybatis_plus_demo是你要使用的数据库名称。
MyBatisPlus配置
在你的application.properties或application.yml文件中添加MyBatisPlus配置:
mybatis-plus:
# 配置Mapper扫描路径
mapper-locations: classpath:mapper/*.xml
# 配置实体类包路径
typeAliasesPackage: com.example.demo.entity
# 配置逻辑删除字段
global-config:
db-config:
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
在上述代码中,mapper-locations用于指定Mapper接口的XML文件路径,typeAliasesPackage用于指定实体类的包路径,global-config中的db-config用于配置逻辑删除字段。
代码生成器配置
MyBatisPlus提供了一个代码生成器,可以根据数据库表自动生成实体类、Mapper接口和XML文件。你可以在你的项目中添加一个代码生成器(例如generator包),并在generator包下创建一个GeneratorConfig类:
public class GeneratorConfig {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("your name");
gc.setOpen(false);
gc.setServiceName("%sService");
gc.setIdType(IdType.AUTO);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus_demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example.demo");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setLogicDeleteFieldName("deleted");
mpg.setStrategy(strategy);
// 执行生成
mpg.execute();
}
}
在上述代码中,我们使用了AutoGenerator类来生成代码。我们可以通过设置GlobalConfig、DataSourceConfig、PackageConfig和StrategyConfig来配置生成器。
使用
实体类
我们可以使用@TableName注解来指定实体类对应的数据库表名,使用@TableId注解来指定主键生成策略。
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@TableLogic
private Integer deleted;
}
在上述代码中,@TableLogic注解用于指定逻辑删除字段。
Mapper接口
我们可以使用BaseMapper接口提供的方法来进行数据库操作,例如selectById、selectList、insert、updateById和deleteById等。
public interface UserMapper extends BaseMapper<User> {
}
在上述代码中,UserMapper继承了BaseMapper接口,它提供了很多便捷的方法。
Service类
在Service类中,我们可以使用@Autowired注解来注入UserMapper接口,并使用它来进行数据库操作。
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getById(Long id) {
return userMapper.selectById(id);
}
public List<User> list() {
return userMapper.selectList(null);
}
public boolean save(User user) {
return userMapper.insert(user) > 0;
}
public boolean update(User user) {
return userMapper.updateById(user) > 0;
}
public boolean removeById(Long id) {
return userMapper.deleteById(id) > 0;
}
}
在上述代码中,我们通过@Autowired注解注入了UserMapper接口,并使用它来进行数据库操作。例如,getById方法使用selectById方法查询单个用户,list方法使用selectList方法查询所有用户,save方法使用insert方法插入新用户,update方法使用updateById方法更新用户信息,removeById方法使用deleteById方法删除用户。
Controller类
在Controller类中,我们可以使用@Autowired注解来注入UserService类,并使用它来处理HTTP请求。
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.getById(id);
}
@GetMapping("/")
public List<User> list() {
return userService.list();
}
@PostMapping("/")
public boolean save(@RequestBody User user)