Mybatis-Plus 通用CRUD的詳細(xì)操作
通過前面的學(xué)習(xí),我們了解到通過繼承BaseMapper就可以獲取到各種各樣的單表操作,接下來我們將詳細(xì)講解這些
操作。
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ù)庫。
如何設(shè)置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), /** * 該類型為未設(shè)置主鍵類型 */ NONE(1), /** * 用戶輸入ID * <p>該類型可以通過自己注冊自動填充插件進(jìn)行填充</p> */ INPUT(2), /* 以下3種類型、只有當(dāng)插入對象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)//設(shè)置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); } }
結(jié)果:
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進(jìn)行更新:
@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); }
測試結(jié)果:
均可達(dá)到更新的效果。
關(guān)于wrapper更多的用法后面會詳細(xì)講解。
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中的元素設(shè)置為刪除的條件,多個之間為and關(guān)系 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("張三"); //將實體對象進(jìn)行包裝,包裝為操作條件 QueryWrapper<User> wrapper = new QueryWrapper<>(user); int result = this.userMapper.delete(wrapper); System.out.println("result = " + result); }
結(jié)果:
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); }
結(jié)果:
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); }
結(jié)果:
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ù),如果結(jié)果超過一條會報錯 User user = this.userMapper.selectOne(wrapper); System.out.println(user); }
結(jié)果:
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") //設(shè)置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); } }
結(jié)果:
5 SQL注入的原理
前面我們已經(jīng)知道,MP在啟動后會將BaseMapper中的一系列的方法注冊到mappedStatements中,那么究竟是如
何注入的呢?流程又是怎么樣的?下面我們將一起來分析下。
在MP中,ISqlInjector負(fù)責(zé)SQL的注入工作,它是一個接口,AbstractSqlInjector是它的實現(xiàn)類,實現(xiàn)關(guān)系如下:
在AbstractSqlInjector中,主要是由inspectInject()方法進(jìn)行注入的,如下:
@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)); 是關(guān)鍵,循環(huán)遍歷方法,進(jìn)行注入。
最終調(diào)用抽象方法injectMappedStatement進(jìn)行真正的注入:
/** * 注入自定義 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中。
到此這篇關(guān)于Mybatis-Plus 通用CRUD的文章就介紹到這了,更多相關(guān)Mybatis-Plus 通用CRUD內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Mybatis實現(xiàn)增刪改查(CRUD)實例代碼
- Mybatis實現(xiàn)數(shù)據(jù)的增刪改查實例(CRUD)
- Spring Boot整合Mybatis并完成CRUD操作的實現(xiàn)示例
- Spring boot整合Mybatis實現(xiàn)級聯(lián)一對多CRUD操作的完整步驟
- 基于Mybatis-Plus的CRUD的實現(xiàn)
- MyBatis Plus配置日志CRUD的使用詳解
- MybatisPlus,無XML分分鐘實現(xiàn)CRUD操作
- mybatisplus?復(fù)合主鍵(多主鍵)?CRUD示例詳解
- MyBatis實現(xiàn)CRUD的示例代碼
相關(guān)文章
String實例化及static final修飾符實現(xiàn)方法解析
這篇文章主要介紹了String實例化及static final修飾符實現(xiàn)方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09Java 獲取當(dāng)前設(shè)備的 IP 地址(最新推薦)
Internet 協(xié)議 (IP) 地址可以是連接到 TCP/IP 網(wǎng)絡(luò)的每個設(shè)備的標(biāo)識符,該標(biāo)識符用于識別和定位中間通信的節(jié)點,這篇文章主要介紹了在 Java 中獲取當(dāng)前設(shè)備的 IP 地址,需要的朋友可以參考下2023-06-06簡述JAVA中堆內(nèi)存與棧內(nèi)存的區(qū)別
這篇文章主要介紹了JAVA中堆內(nèi)存與棧內(nèi)存的區(qū)別,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07基于IDEA 的遠(yuǎn)程調(diào)試 Weblogic的操作過程
這篇文章主要介紹了基于IDEA 的遠(yuǎn)程調(diào)試 Weblogic的操作過程,本文通過圖文實例相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09Spring?MVC和springboot靜態(tài)資源處理問題
這篇文章主要介紹了Spring?MVC和springboot靜態(tài)資源處理問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08