对于Java开发岗位,CRUD是工作中基础中的基础,因为已经准入职了,所以趁毕业前学习一下,大家可以关注鱼皮加入鱼皮的星球哦~

增加

以User类为例,增加的方法一共有一下7种

截屏2023-03-17 23.43.52先来看最简单的save方法

1
2
3
default boolean save(T entity) {
return SqlHelper.retBool(this.getBaseMapper().insert(entity));
}

传入一个实体(一行数据),将这行数据插入到数据表中,成功返回true,失败返回false

saveBatch方法有两种实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Transactional(
rollbackFor = {Exception.class}
)
default boolean saveBatch(Collection<T> entityList) {
return this.saveBatch(entityList, 1000);
}
@Transactional(
rollbackFor = {Exception.class}
)
public boolean saveBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = this.getSqlStatement(SqlMethod.INSERT_ONE);
return this.executeBatch(entityList, batchSize, (sqlSession, entity) -> {
sqlSession.insert(sqlStatement, entity);
});
}

可以发现两者的差异就是batchSize的值,这个用默认的就好,这个方法将数据批量插入到数据表中,需要将这些数据封装成一个列表,然后批处理将这些数据一个个插入到数据表中,同样地,插入成功返回true,失败返回false,因为多条数据需要满足事务的定义,所以需要加上事务的注解

saveOrUpdate也有两种实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
default boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper) {
return this.update(entity, updateWrapper) || this.saveOrUpdate(entity);
}
@Transactional(
rollbackFor = {Exception.class}
)
public boolean saveOrUpdate(T entity) {
if (null == entity) {
return false;
} else {
TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass);
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!", new Object[0]);
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!", new Object[0]);
Object idVal = tableInfo.getPropertyValue(entity, tableInfo.getKeyProperty());
return !StringUtils.checkValNull(idVal) && !Objects.isNull(this.getById((Serializable)idVal)) ? this.updateById(entity) : this.save(entity);
}
}

第一个实现传入了一个更新条件,因为插入和更新只能成功一个,所以只要有一个操作成功了就返回true,否则返回false,第二个方法仅传入实体类,可以发现代码比较复杂,总之就是根据主键找数据,找到了说明表中已经有了,那就更新,找不到则说明没有,那就插入,同样成功返回true,失败返回false,那么为什么单条数据还要加事务注解呢?

删除

修改

查询