Spring Boot 2.X(十九):集成 mybatis-plus 高效開發


前言

之前介紹了 SpringBoot 整合 Mybatis 實現數據庫的增刪改查操作,分別給出了 xml 和注解兩種實現 mapper 接口的方式;雖然注解方式干掉了 xml 文件,但是使用起來並不優雅,本文將介紹 mybats-plus 的常用實例,簡化常規的 CRUD 操作。

mybatis-plus

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

學習 mybatis-plus:https://mp.baomidou.com/guide

常用實例

1. 項目搭建

1.1 pom.xml

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		
		<!-- 熱部署模塊 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional> <!-- 這個需要為 true 熱部署才有效 -->
		</dependency>

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.3.0</version>
		</dependency>
	</dependencies>

1.2 application.yaml

# spring setting
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: zwqh@0258

1.3 實體類 UserEntity

@TableName(value="t_user")
public class UserEntity {

	@TableId(value="id",type=IdType.AUTO)
	private Long id;
	private String userName;
	private String userSex;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserSex() {
		return userSex;
	}
	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}
	
}

@TableName 指定數據庫表名,否則默認查詢表會指向 user_entity ;@TableId(value="id",type=IdType.AUTO) 指定數據庫主鍵,否則會報錯。

1.4 Dao層 UserDao

繼承 BaseMapper ,T表示對應實體類

public interface UserDao extends BaseMapper<UserEntity>{

}

1.5 啟動類

在啟動類添加 @MapperScan 就不用再 UserDao 上用 @Mapper 注解。

@SpringBootApplication
@MapperScan("cn.zwqh.springboot.dao")
public class SpringBootMybatisPlusApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootMybatisPlusApplication.class, args);
	}

}

1.6 分頁插件配置

@Configuration
public class MybatisPlusConfig {
	 /**
     *   mybatis-plus分頁插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }
 
}

2.示例

2.1 新增

新增用戶
UserEntity user=new UserEntity();
user.setUserName("朝霧輕寒");
user.setUserSex("男");
userDao.insert(user);         

2.2 修改

根據id修改用戶
UserEntity user=new UserEntity();
user.setUserName("朝霧輕曉");
user.setUserSex("男");
user.setId(25L);
userDao.updateById(user);
根據entity條件修改用戶
UserEntity user=new UserEntity();
user.setUserSex("女");
userDao.update(user,new QueryWrapper<UserEntity>().eq("user_name", "朝霧輕寒"));

2.3 查詢

根據id查詢用戶
UserEntity user = userDao.selectById(id);
根據entity條件查詢總記錄數
int count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("user_sex", "男"));
根據 entity 條件,查詢一條記錄,返回的是實體
QueryWrapper<UserEntity> queryWrapper=new QueryWrapper<UserEntity>();
		UserEntity user=new UserEntity();
		user.setUserName("朝霧輕寒");
		user.setUserSex("男");
		queryWrapper.setEntity(user);
user = userDao.selectOne(queryWrapper);		

如果表內有兩條或以上的相同數據則會報錯,可以用來判斷某類數據是否已存在

根據entity條件查詢返回第一個字段的值(返回id列表)
QueryWrapper<UserEntity> queryWrapper=new QueryWrapper<UserEntity>();
		UserEntity user=new UserEntity();
		user.setUserSex("男");
		queryWrapper.setEntity(user);
List<Object> objs= userDao.selectObjs(queryWrapper);	
根據map條件查詢返回多條數據
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_name", username);
		map.put("user_sex",sex);
List<UserEntity> list = userDao.selectByMap(map);		
根據entity條件查詢返回多條數據(List
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_sex","男");
List<UserEntity> list = userDao.selectList(new QueryWrapper<UserEntity>().allEq(map));		
根據entity條件查詢返回多條數據(List<Map<String, Object>> )
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_sex","男");
List<Map<String, Object>> list = userDao.selectMaps(new QueryWrapper<UserEntity>().allEq(map));
根據ID批量查詢
List<Long> ids=new ArrayList<Long>();
		ids.add(1L);
		ids.add(2L);
		ids.add(3L);
List<UserEntity> list = userDao.selectBatchIds(ids);	

主鍵ID列表(不能為 null 以及 empty)

分頁查詢
Page<UserEntity> page=userDao.selectPage(new Page<>(1,5), new QueryWrapper<UserEntity>().eq("user_sex", "男"));
Page<Map<String, Object>> page=userDao.selectMapsPage(new Page<>(1,5), new QueryWrapper<UserEntity>().eq("user_sex", "男"));

需先配置分頁插件bean,否則分頁無效。如有pagehelper需先去除,以免沖突。

new Page<>(1,5),1表示當前頁,5表示頁面大小。

2.4 刪除

根據id刪除用戶
userDao.deleteById(1);
根據entity條件刪除用戶
userDao.delete(new QueryWrapper<UserEntity>().eq("id", 1));
根據map條件刪除用戶
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_name", "zwqh");
		map.put("user_sex","男");
		userDao.deleteByMap(map);
根據ID批量刪除
List<Long> ids=new ArrayList<Long>();
		ids.add(1L);
		ids.add(2L);
		ids.add(3L);
		userDao.deleteBatchIds(ids);

主鍵ID列表(不能為 null 以及 empty)

小結

本文介紹了 mybatis-plus 相關的 Mapper層 CRUD 接口實現,其還提供了 Service層 CRUD 的相關接口,有興趣的小伙伴可以去使用下。 mybatis-plus 真正地提升了擼碼效率。

其他學習要點:

  1. mybatis-plus 條件構造器
  2. lamda 表達式
  3. 常用注解
  4. ...

學習地址:https://mp.baomidou.com/guide/

示例代碼

github

碼雲

非特殊說明,本文版權歸 朝霧輕寒 所有,轉載請注明出處.

原文標題:Spring Boot 2.X(十九):集成 mybatis-plus 高效開發

原文地址: https://www.zwqh.top/article/info/33

如果文章有不足的地方,歡迎提點建議,后續會完善~

如果文章對您有幫助,請給我點個贊哦~

關注下我的公眾號,文章持續更新中...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM