# MyBatis-Plus学习
**Repository Path**: cx293824/my-base-plus-learning
## Basic Information
- **Project Name**: MyBatis-Plus学习
- **Description**: MyBatis-Plus小白从入门到高级学习
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2024-04-14
- **Last Updated**: 2024-04-15
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# 导入说明
新建一个空项目,将本项目导入空项目下
**快速入门及数据库导入请移步官网** [MyBatisPlus快速开始](https://baomidou.com/pages/226c21/#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B)
具体方法请可查询[**官方文档**](https://baomidou.com/pages/49cc81/#service-crud-%E6%8E%A5%E5%8F%A3)配合测试使用,本文不赘述
# 基于Mapper接口CRUD
> 通用 CRUD 封装[BaseMapper (opens new window)](https://gitee.com/baomidou/mybatis-plus/blob/3.0/mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/mapper/BaseMapper.java)接口, `Mybatis-Plus` 启动时自动解析实体表关系映射转换为 `Mybatis` 内部对象注入容器! 内部包含常见的单表操作!
## 实现测试案例
1. 创建项目,导入依赖
```xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.0.5
com.example
curd-mapper
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
com.baomidou
mybatis-plus-boot-starter
3.5.3.1
org.springframework.boot
spring-boot-starter-jdbc
com.alibaba
druid-spring-boot-3-starter
1.2.20
mysql
mysql-connector-java
8.0.28
org.projectlombok
lombok
1.18.28
org.springframework.boot
spring-boot-maven-plugin
```
2. 实体类pojo
```java
@TableName(value ="user")
@Data
public class User implements Serializable {
private Long id;
private String name;
private Integer age;
private String email;
private static final long serialVersionUID = 1L;
}
```
3. **创建接口并继承BaseMapper**
4. 配置SpringBoot
```yaml
# 连接池配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://localhost:3306/mybatis-example
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 控制台输出sql语句
```
5. 创建测试类
```java
@SpringBootTest(classes = MainApplication.class)
public class Mytest {
@Autowired
private UserMapper userMapper;
@Test
public void test_insert(){
User user = new User();
user.setAge(18);
user.setName("aimiliya");
user.setEmail("xxxx.email");
//baseMapper提供的数据库插入方法
int row = userMapper.insert(user);
}
@Test
public void test_delete(){
//根据id删除
int rows = userMapper.deleteById(1687124343556005889L);
System.out.println("rows = " + rows);
//根据age = 20
Map param = new HashMap();
param.put("age",20); // age = 20 and name = xx
int i = userMapper.deleteByMap(param);
System.out.println("i = " + i);
//wrapper 条件封装对象,无限的封装条件
//userMapper.delete(wrapper);
}
@Test
public void test_update(){
//TODO: update 当属性值为null的时候,不修改!
//updatebyId 实体类id必须有值
//user id = 1 age改为30
User user = new User();
user.setId(1L);
user.setAge(30);
// update user set age = 30 where id = 1
int i = userMapper.updateById(user);
System.out.println("i = " + i);
//将所有人的年龄改为22
//update 实体类可以没有id值
User user1 = new User();
user1.setAge(22);
int rows = userMapper.update(user,null); //null没条件
System.out.println("rows = " + rows);
}
@Test
public void test_select(){
User user = userMapper.selectById(1);
System.out.println("user = " + user);
//ids集合查询
List ids = new ArrayList<>();
ids.add(1L); ids.add(2L);
List users = userMapper.selectBatchIds(ids);
System.out.println("users = " + users);
}
}
```
## 自定义和多表映射
mybatis-plus的默认mapperxml位置
```yaml
mybatis-plus: # mybatis-plus的配置
# 默认位置 private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};
mapper-locations: classpath:/mapper/*.xml
```
自定义mapper方法:
```java
public interface UserMapper extends BaseMapper {
//正常自定义方法!
//可以使用注解@Select或者mapper.xml实现
List queryAll();
}
```
基于mapper.xml实现:
```xml
```
# 基于Service接口CRUD
## 对比Mapper接口CRUD区别:
- service添加了批量方法
- service层的方法自动添加事务
### 使用Iservice接口方式(具体使用请查看代码 :blush: )
接口继承IService接口
```java
public interface UserService extends IService {
}
```
类继承ServiceImpl实现类
```java
@Service
public class UserServiceImpl extends ServiceImpl implements UserService{
}
```
测试:
```java
@SpringBootTest(classes = MainApplication.class)
public class MyBatisPlusTest {
@Autowired
private UserService userService;
@Test
public void test_save(){
List list = new ArrayList<>();
User user = new User();
user.setAge(18);
user.setEmail("xx.email.com");
user.setName("艾米莉亚");
list.add(user);
User user1 = new User();
user1.setAge(18);
user1.setEmail("jj.e");
user1.setName("486");
list.add(user1);
boolean b = userService.saveBatch(list);
System.out.println("b = " + b);
}
@Test
public void test_saveOrUpdate(){
//如果有id有值 不为null,修改 为null插入
User user = new User();
user.setId(1L);
user.setAge(18);
user.setEmail("jj");
user.setName("拉姆");
userService.saveOrUpdate(user);
}
@Test
public void test_remove(){
boolean b = userService.removeById(1687120798123302914L);
System.out.println("b = " + b);
}
@Test
public void test_update(){
User user = new User();
user.setId(1L);
user.setAge(18);
user.setEmail("jj");
user.setName("蕾姆");
userService.updateById(user);
}
@Test
public void test_getOrList(){
User byId = userService.getById(1L);//get返回的是单个对象
System.out.println("byId = " + byId);
List list = userService.list(null);//查询全部,返回的集合
System.out.println("list = " + list);
}
}
```
## CRUD方法介绍
```Java
保存:
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection entityList);
// 插入(批量),batchSize表示每批次保存的实体数量。通过指定批量大小,可以控制一次提交的实体数量
boolean saveBatch(Collection entityList, int batchSize);
修改或者保存:
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection entityList, int batchSize);
移除:
// 根据 queryWrapper 设置的条件,删除记录
boolean remove(Wrapper queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection extends Serializable> idList);
更新:
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection entityList, int batchSize);
数量:
// 查询总记录数
int count();
// 根据 Wrapper 条件,查询总记录数
int count(Wrapper queryWrapper);
查询:
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map getMap(Wrapper queryWrapper);
// 根据 Wrapper,查询一条记录
V getObj(Wrapper queryWrapper, Function super Object, V> mapper);
集合:
// 查询所有
List list();
// 查询列表
List list(Wrapper queryWrapper);
// 查询(根据ID 批量查询)
Collection listByIds(Collection extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection listByMap(Map columnMap);
// 查询所有列表
List