Mybatis-Plus 通用CRUD的詳細操作
通過前面的學習,我們了解到通過繼承BaseMapper就可以獲取到各種各樣的單表操作,接下來我們將詳細講解這些
操作。

1、插入操作
1.1 方法定義
/*** 插入一條記錄 * @param entity 實體對象 */ int insert(T entity);
1.2 測試用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUserMapper {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert(){
User user=new User();
user.setAge(12);
user.setName("曹操");
user.setPassword("123");
user.setMail("caocao@qq.com");
user.setUserName("曹操");
user.setAddress("北京");
//result數(shù)據(jù)庫受影響的行數(shù)
int result = userMapper.insert(user);
System.out.println("result=>"+result);
//獲取自增長后的id值
System.out.println(user.getId());//自增后的id會回填到對象中
}
}
1.3 測試


可以看到,數(shù)據(jù)已經(jīng)寫入到了數(shù)據(jù)庫,但是,id的值不正確,我們期望的是數(shù)據(jù)庫自增長,實際是MP生成了id的值
寫入到了數(shù)據(jù)庫。
如何設置id的生成策略呢?
MP支持的id策略
package com.baomidou.mybatisplus.annotation;
import lombok.Getter;
/**
* 生成ID類型枚舉類
*
* @author hubin
* @since 2015-11-10
*/
@Getter
public enum IdType {
/**
* 數(shù)據(jù)庫ID自增
*/
AUTO(0),
/**
* 該類型為未設置主鍵類型
*/
NONE(1),
/**
* 用戶輸入ID
* <p>該類型可以通過自己注冊自動填充插件進行填充</p>
*/
INPUT(2),
/* 以下3種類型、只有當插入對象ID 為空,才自動填充。 */
/**
* 全局唯一ID (idWorker)
*/
ID_WORKER(3),
/**
* 全局唯一ID (UUID)
*/
UUID(4),
/**
* 字符串全局唯一ID (idWorker 的字符串表示)
*/
ID_WORKER_STR(5);
private final int key;
IdType(int key) {
this.key = key;
}
}
修改User對象:
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
@TableId(value="id",type= IdType.AUTO)//設置id字段為自增長
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
數(shù)據(jù)插入成功:

1.4 @TableField
在MP中通過@TableField注解可以指定字段的一些屬性,常常解決的問題有2個:
1、對象中的屬性名和字段名不一致的問題(非駝峰)
2、對象中的屬性字段在表中不存在的問題
使用:

其他用法,如密碼字段不加入查詢字段:

效果:
.
2、更新操作
在MP中,更新操作有2種,一種是根據(jù)id更新,另一種是根據(jù)條件更新。
2.1 根據(jù)id更新
方法定義:
/*** 根據(jù) ID 修改 ** @param entity 實體對象 */ int updateById(@Param(Constants.ENTITY) T entity);
測試:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired private UserMapper userMapper;
@Test
public void testUpdateById() {
User user = new User(); user.setId(6L); //主鍵
user.setAge(21); //更新的字段
//根據(jù)id更新,更新不為null的字段
this.userMapper.updateById(user);
}
}
結果:


2.2 根據(jù)條件更新
方法定義:
/*** 根據(jù) whereEntity 條件,更新記錄 ** @param entity 實體對象 (set 條件值,可以為 null) * @param updateWrapper 實體對象封裝操作類(可以為 null,里面的 entity 用于生成 where 語句) */ int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
測試用例:
@Test public void testUpdate() {
User user = new User(); user.setAge(22); //更新的字段
//更新的條件
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("id", 6);
//執(zhí)行更新操作
int result = this.userMapper.update(user, wrapper);
System.out.println("result = " + result);
}
或者,通過UpdateWrapper進行更新:
@Test public void testUpdate() {
//更新的條件以及字段
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.eq("id", 6).set("age", 23);
//執(zhí)行更新操作
int result = this.userMapper.update(null, wrapper);
System.out.println("result = " + result);
}
測試結果:

均可達到更新的效果。
關于wrapper更多的用法后面會詳細講解。
3、刪除操作
3.1 deleteById
方法定義:
/*** 根據(jù) ID 刪除 ** @param id 主鍵ID */ int deleteById(Serializable id);
測試用例:
@Test
public void testDeleteById() {
//執(zhí)行刪除操作
int result = this.userMapper.deleteById(6L);
System.out.println("result = " + result);
}

數(shù)據(jù)被刪除。
3.2 deleteByMap
方法定義:
/*** 根據(jù) columnMap 條件,刪除記錄 ** @param columnMap 表字段 map 對象 */ int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
測試用例:
@Test
public void testDeleteByMap() {
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("age",20); columnMap.put("name","張三");
//將columnMap中的元素設置為刪除的條件,多個之間為and關系
int result = this.userMapper.deleteByMap(columnMap);
System.out.println("result = " + result);
}

3.3 delete
方法定義:
/*** 根據(jù) entity 條件,刪除記錄 ** @param wrapper 實體對象封裝操作類(可以為 null) */ int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
測試用例:
@Test public void testDeleteByMap() {
User user = new User();
user.setAge(20);
user.setName("張三");
//將實體對象進行包裝,包裝為操作條件
QueryWrapper<User> wrapper = new QueryWrapper<>(user);
int result = this.userMapper.delete(wrapper);
System.out.println("result = " + result);
}
結果:

3.4 deleteBatchIds
方法定義:
/*** 刪除(根據(jù)ID 批量刪除) ** @param idList 主鍵ID列表(不能為 null 以及 empty) */ int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
測試用例:
@Test
public void testDeleteByMap() {
//根據(jù)id集合批量刪除
int result = this.userMapper.deleteBatchIds(Arrays.asList(1L,10L,20L));
System.out.println("result = " + result);
}
結果:

4、查詢操作
MP提供了多種查詢操作,包括根據(jù)id查詢、批量查詢、查詢單條數(shù)據(jù)、查詢列表、分頁查詢等操作。
4.1 selectById
方法定義:
/*** 根據(jù) ID 查詢 ** @param id 主鍵ID */ T selectById(Serializable id);
測試用例:
@Test
public void testSelectById() {
//根據(jù)id查詢數(shù)據(jù)
User user = this.userMapper.selectById(2L);
System.out.println("result = " + user);
}
結果:

4.2 selectBatchIds
方法定義:
/*** 查詢(根據(jù)ID 批量查詢) ** @param idList 主鍵ID列表(不能為 null 以及 empty) */ List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
測試用例:
@Test
public void testSelectBatchIds() {
//根據(jù)id集合批量查詢
List<User> users = this.userMapper.selectBatchIds(Arrays.asList(2L, 3L, 10L));
for (User user : users) {
System.out.println(user);
}
}

4.3 selectOne
方法定義:
/*** 根據(jù) entity 條件,查詢一條記錄 ** @param queryWrapper 實體對象封裝操作類(可以為 null) */ T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
測試用例:
@Test public void testSelectOne() {
QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.eq("name", "李四");
//根據(jù)條件查詢一條數(shù)據(jù),如果結果超過一條會報錯
User user = this.userMapper.selectOne(wrapper);
System.out.println(user);
}
結果:

4.4 selectCount
方法定義:
/*** 根據(jù) Wrapper 條件,查詢總記錄數(shù) ** @param queryWrapper 實體對象封裝操作類(可以為 null) */ Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
測試用例:
@Test
public void testSelectCount() {
QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 23); //年齡大于23歲
//根據(jù)條件查詢數(shù)據(jù)條數(shù)
Integer count = this.userMapper.selectCount(wrapper);
System.out.println("count = " + count);
}

4.5 selectList
方法定義:
/*** 根據(jù) entity 條件,查詢?nèi)坑涗?** @param queryWrapper 實體對象封裝操作類(可以為 null) */ List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
測試用例:
@Test
public void testSelectList() {
QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 23); //年齡大于23歲
//根據(jù)條件查詢數(shù)據(jù)
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println("user = " + user);
}
}

4.6 selectPage
方法定義:
/*** 根據(jù) entity 條件,查詢?nèi)坑涗洠ú⒎摚? ** @param page 分頁查詢條件(可以為 RowBounds.DEFAULT) * @param queryWrapper 實體對象封裝操作類(可以為 null) */ IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
配置分頁插件:
package cn.itcast.mp;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("cn.itcast.mp.mapper") //設置mapper接口的掃描包
public class MybatisPlusConfig {
/*** 分頁插件 */
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
測試用例:
@Test
public void testSelectPage() {
QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 20); //年齡大于20歲
Page<User> page = new Page<>(1,1);
//根據(jù)條件查詢數(shù)據(jù)
IPage<User> iPage = this.userMapper.selectPage(page, wrapper);
System.out.println("數(shù)據(jù)總條數(shù):" + iPage.getTotal());
System.out.println("總頁數(shù):" + iPage.getPages());
List<User> users = iPage.getRecords();
for (User user : users) {
System.out.println("user = " + user);
}
}
結果:

5 SQL注入的原理
前面我們已經(jīng)知道,MP在啟動后會將BaseMapper中的一系列的方法注冊到mappedStatements中,那么究竟是如
何注入的呢?流程又是怎么樣的?下面我們將一起來分析下。
在MP中,ISqlInjector負責SQL的注入工作,它是一個接口,AbstractSqlInjector是它的實現(xiàn)類,實現(xiàn)關系如下:

在AbstractSqlInjector中,主要是由inspectInject()方法進行注入的,如下:
@Override
public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
Class<?> modelClass = extractModelClass(mapperClass);
if (modelClass != null) {
String className = mapperClass.toString();
Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
if (!mapperRegistryCache.contains(className)) {
List<AbstractMethod> methodList = this.getMethodList();
if (CollectionUtils.isNotEmpty(methodList)) {
TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass);
// 循環(huán)注入自定義方法
methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
} else {
logger.debug(mapperClass.toString() + ", No effective injection method was found.");
}
mapperRegistryCache.add(className);
}
}
}
在實現(xiàn)方法中, methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo)); 是關鍵,循環(huán)遍歷方法,進行注入。
最終調(diào)用抽象方法injectMappedStatement進行真正的注入:
/**
* 注入自定義 MappedStatement
*
* @param mapperClass mapper 接口
* @param modelClass mapper 泛型
* @param tableInfo 數(shù)據(jù)庫表反射信息
* @return MappedStatement
*/
public abstract MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo);
查看該方法的實現(xiàn):

以SelectById為例查看:

可以看到,生成了SqlSource對象,再將SQL通過addSelectMappedStatement方法添加到mappedStatements中。

到此這篇關于Mybatis-Plus 通用CRUD的文章就介紹到這了,更多相關Mybatis-Plus 通用CRUD內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot集成iText實現(xiàn)電子簽章功能
這篇文章主要為大家詳細介紹了SpringBoot如何集成iText實現(xiàn)電子簽章功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-10-10
springboot多數(shù)據(jù)源配置及切換的示例代碼詳解
這篇文章主要介紹了springboot多數(shù)據(jù)源配置及切換,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
SpringBoot 將多個Excel打包下載的實現(xiàn)示例
本文主要介紹了SpringBoot 將多個Excel打包下載的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-12-12
關于json序列化(javaBean轉Json的細節(jié)處理)
這篇文章主要介紹了關于json序列化(javaBean轉Json的細節(jié)處理),具有很好的參考價值,希望對大家有所幫助。2022-03-03

