常用配置
mybatis-plus:
configuration:
#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
map-underscore-to-camel-case: true
# 开启 MyBatis-Plus 的下划线转驼峰命名映射功能
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 设置 MyBatis-Plus 的日志实现类为标准输出
global-config:
db-config:
id-type: ASSIGN_ID
# Mybatis-Pluse使用雪花算法自动生成id
IService
作用
IService是一个泛型接口,定义了一系列通用的基础方法,这些方法涵盖了常见的增删改查(CRUD)操作。通过实现IService接口,开发者可以快速构建服务层,并简化数据库操作的编码工作。
boolean save(T entity):将一个实体对象保存到数据库中
T getOne(Wrapper<T> querryWapper):根据查询条件获得单个实体对象
boolean removeById(Serializable id):根据id删除某个实体对象
int count(Wrapper<T> querryWrapper):统计数量
boolean updateById(T entity):更新数据库表
BaseMapper
作用
BaseMapper是MyBatis-Plus框架中的一个核心接口,它主要用于简化数据访问层(mapper)的编写,提供了一系列基本的CRUD(创建、读取、更新、删除)方法,帮助开发者进行数据库操作而无需手动编写对应的SQL语句。
ServiceImpl
ServiceImpl是一个类
ServiceImpl可以重写IService中的方法
ServiceImpl<M,T>:M表示Mapper接口类型,T表示实体类类型,它可以直接访问BaseMapper接口的方法,从而实现对数据库的操作
使用方法
1.定义一个实体类User
首先,我们需要为数据库中的用户表创建一个实体类。这个类通常包含与数据库表中的列相对应的字段,以及getter和setter方法。
package com.example.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
// 其他字段...
}
2.创建Mapper接口
接下来,我们需要创建一个Mapper接口,这个接口将继承自MyBatis Plus的BaseMapper接口。BaseMapper接口提供了一系列基础的数据库操作方法,如select、insert、update和delete等。r
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 可以添加自定义的查询方法...
}
3.创建Service接口和实现类
然后,我们需要创建一个服务接口(UserService)和实现类(UserServiceImpl)。服务接口将继承自IService接口,并指定泛型类型为User。实现类将继承自ServiceImpl类,并实现UserService接口。
package com.example.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.entity.User;
public interface UserService extends IService<User> {
// 可以添加自定义的服务方法...
}
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
// 可以添加自定义的服务方法实现...
}
UserService继承了IService里的crud抽象方法
UserServiceImpl继承了ServiceImpl,ServiceImpl帮忙重写了IService里的抽象方法
4.在Controller中使用服务
最后,我们可以在Controller层中使用UserService来进行数据库操作。通过注入UserService,我们可以调用其提供的方法来实现具体的业务逻辑。
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/save")
public boolean saveUser(@RequestBody User user) {
return userService.save(user);
}
@DeleteMapping("/delete/{id}")
public boolean deleteUser(@PathVariable Long id) {
return userService.removeById(id);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getById(id);
}
@GetMapping("/list")
public List<User> getAllUsers() {
return userService.list();
}
// 其他控制器方法...
}
LambdaQuerryWrapper
作用
LambdaQueryWrapper是MyBatis-Plus框架中的一个查询构造器。LambdaQueryWrapper主要用于构建基于Lambda表达式的查询条件,从而避免手写SQL语句的繁琐和容易出错的问题。它提供了一系列用于构建查询条件的方法,如eq(等于)、ne(不等于)、like(模糊查询)、in(范围查询)等。
queryMapper.orderByDesc(boolean condition,R column,object value):对查询结果进行降序排列
queryMapper.like(boolean condition,R column,object value):模糊查询
queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
queryMapper.eq(boolean condition,R column,object value) :筛选出满足该属性等于给定值的记录
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.Employee;
public class EmployeeQueryExample {
public static void main(String[] args) {
// 创建查询包装器
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
// 添加相等条件,查询用户名等于"john"的员工记录
queryWrapper.eq(Employee::getUsername, "john");
// 假设这里有一个数据库操作对象,可以执行查询
// Employee employee = employeeDao.selectOne(queryWrapper);
// 如果存在满足条件的记录,employee 将包含查询结果
}
}
分页插件paginationInnerInterceptor
在 Web 应用中,分页可以让用户更方便地浏览大量数据。用户可以通过点击页码或上一页 / 下一页按钮来逐步查看数据
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis-Plus 配置类。
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
// 创建 MyBatis-Plus 拦截器实例。
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分页拦截器到 MyBatis-Plus 拦截器中。
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
Page类
Page 类是 MyBatis-Plus 提供的一个分页对象,用于封装分页查询的参数和结果。
Page类的主要属性:
page:总页数
pageSize:每页显示的记录数
name:当前页数
@TableField
1.成员变量名与数据库字段名不一致
假设数据库表中有一个字段名为user_name,而你的实体类属性名为username,可以使用@TableField("user_name")来建立正确的映射。
2.成员变量不是数据库字段
假设实体类的成员变量有address,而数据库表中没有这个字段,可以使用
@TableField("exist = false")
3.公共字段自动填充
@TableField(fill = FieldFill.INSERT)表示在插入数据时自动填充该属性的值。
@TableField(fill = FieldFill.INSERT_UPDSTE)表示在插入和更新数据时自动填充该属性的值。
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
@DATA
@TableName("user_table")
public class User {
private Long id;
@TableField("user_name")
private String username;
@TableField(exist = false)
private String address;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}