【MyBatisPlus筆記整理三】CRUD詳解

版權聲明:本文爲 小異常 原創文章,非商用自由轉載-保持署名-註明出處,謝謝!
本文網址:https://blog.csdn.net/sun8112133/article/details/106917361







本篇博客是 MyBatis Plus 中的核心內容,將會爲大家講解 CRUD 操作。


一、準備工作

先準備一張表和對應的實體類以及 Mapper。

1、數據表

create table `t_user` (
	`id` int(11) not null auto_increment,
	`name` varchar(255),
	`age` int(11),
	primary key (`id`)
);

-- 隨意插入幾條記錄

2、實體類

@Data
@TableName("t_user")
public class User {
    @TableId(type=IdType.INPUT)
    private Integer id;
    private String name;
    private Integer age;
}

3、Mapper

public interface UserMapper extends BaseMapper<User> {
	
}


二、添加

調用 insert() 方法實現添加效果。

  • int insert(T t):添加方法,返回添加的條數。
@Autowired
private UserMapper mapper;

@Test
void save() {
    User user = new User();
    account.setTitle("張三");
    account.setAge(12);
    mapper.insert(user);
    System.out.println(user);
}


三、刪除

1、根據 id 刪除

  • int deleteById(Serializable id):根據單個 id 刪除,返回刪除的條數;
  • int deleteBatchIds(Collection idList):根據多個 id 刪除,返回刪除的條數。
@Test
void delete() {
	// 根據 id 刪除
	mapper.deleteById(1);
	
	// 刪除多個,根據多個id
	mapper.deleteBatchIds(Arrays.asList(1, 2));
}

2、根據條件刪除

  • int delete(Wrapper wrapper):根據指定條件進行刪除,返回刪除的條數;
  • int deleteByMap(Map map):根據指定條件進行刪除,返回刪除的條數。這個條件放到 Map 集合中,Map 中的條件都是以 And 連接的,它只能做等值判斷。
@Test
void delete() {		
    // 根據指定條件進行刪除
    QueryWrapper<User> wrapper = new QueryWrapper();
    wrapper.eq("age", 1);  // 刪除 age 屬性爲 1 的記錄,其中 eq 是等於的意思,類似的還有 lt(小於)、gt(大於)
    mapper.delete(wrapper);

    // 根據條件刪除,條件放到 Map 集合中,Map 中的條件都是以 And 連接的
    Map<String, Object> map = new HashMap<>();
    map.put("id", 5);  // 刪除 id 爲 5 的記錄
    mapper.deleteByMap(map);
}


四、修改

  • int updateById(T entity):根據 id 修改,返回修改的條數;
  • int update(T entity, Wrapper wrapper):根據條件修改,返回修改的條數。
@Test
void update() {
    // 根據 id 修改
    User user = mapper.selectById(1);  // 根據 id 從數據庫中查詢對應的記錄
    account.setName("張三");
    mapper.updateById(user);   // 根據 id 修改

    // 根據條件修改
    User user = mapper.selectById(3);
    user.setName("李四");
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("id", 3);
    mapper.update(user, wrapper);   // 根據 id 爲 3 這個條件進行修改
}


五、查詢

1、根據 id 查詢

  • T selectById(Serializable id):根據單個 id 查詢,返回查詢到的實體對象;
  • List selectBatchIds(Collection idList):根據多個 id 查詢,返回查詢到的實體對象列表。
@Test
void select() {
    // 根據 ID 查詢
    mapper.selectById(2);

    // 根據多個 ID 查詢
    mapper.selectBatchIds(Arrays.asList(2, 3, 5)).forEach(System.out::println);
}

2、根據條件查詢

  • List selectList(Wrapper wrapper):根據指定條件去查詢,返回查詢到的實體對象;
  • List selectByMap(Map map):根據指定條件去查詢,這個條件放到 Map 集合中,它與 selectList() 方法的區別在於 Map 只能做等值判斷,邏輯判斷需要使用 Wrapper 來處理;
  • List<Map> selectMaps(Wrapper wrapper):根據指定條件去查詢,條件使用 Wrapper,它會將結果封裝到 Map 中,它與 selectList() 方法的區別在於,一個是以 Map 集合返回,一個是以實體對象返回。
@Test
void select() {
	// selectList() 方法:
	// 不加任何條件,全部查詢
	mapper.selectList(null);
    
	// 等於條件查詢
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.eq("name", "小紅");
	System.out.println(mapper.selectList(wrapper));
    
	// 多條件查詢
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	Map<String, Object> map = new HashMap<>();
	map.put("name", "小明");
	map.put("age", 2);
	wrapper.allEq(map);
	System.out.println(mapper.selectList(wrapper));
	
	// 小於條件查詢(小於lt,大於gt,小於等於le,大於等於ge)
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.lt("age", 2);
	System.out.println(mapper.selectList(wrapper));

    // 不等於條件查詢
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.ne("age", 2);
	System.out.println(mapper.selectList(wrapper));

	// selectByMap() 方法:
	// 條件查詢,類似 wrapper
	// Map 只能做等值判斷,邏輯判斷需要使用 Wrapper 來處理
	Map<String, Object> map = new HashMap<>();
	map.put("id", "2");
	mapper.selectByMap(map);

	// selectMaps() 方法:
	// 條件查詢 與 selectList() 的區別在於,一個是以 Map集合返回的,一個是以 Account 對象返回的。
	// 將查詢的結果封裝到Map中
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.gt("age", "2");
	mapper.selectMaps(wrapper).forEach(System.out::println);
}

3、分頁查詢

  • Page selectPage(Page page, Wrapper wrapper):根據條件進行分頁查詢;
  • Page selectMapsPage(Page page, Wrapper wrapper):根據條件進行分頁查詢,與 selectPage() 的區別是,一個是以 Map 集合返回的,一個是以實體對象返回的。
@Test
void select() {
	// 分頁查詢
	Page<User> page = new Page<>(1, 2);
	Page<User> result = mapper.selectPage(page, null);
	System.out.println(result.getSize());   // 每頁取2條
	System.out.println(result.getTotal());   // 總記錄數
	result.getRecords().forEach(System.out::println);

	// 分頁查詢,把結果集封裝到 Map 集合中
	// 與 selectPage() 的區別是,一個是以 Map 集合返回的,一個是以實體對象返回的
	Page<Map<String, Object>> page = new Page<>(1, 2);
	mapper.selectMapsPage(page, null).getRecords().forEach(System.out::println);
}

4、查詢所有的主鍵

  • List selectObjs(Wrapper wrapper):根據條件查詢主鍵列表。
@Test
void select() {
	// 查詢所有的主鍵
	mapper.selectObjs(null).forEach(System.out::println);
}	

5、僅查詢一條記錄

注意: 查詢一條記錄,結果集必須是一條記錄,否則就會報錯。

  • T selectOne(Wrapper wrapper):根據條件查詢記錄,必須保證結果集只有一條記錄。
@Test
void select() {
	// 查詢一條記錄,結果集必須是一條記錄,否則就會報錯
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.eq("name", "二號");
	mapper.selectOne(wrapper);
}

6、模糊查詢

模糊查詢 需要在 Wrapper 條件中設置模糊條件,此方法是 Wrapper 的方法。

  • like(String s1, String s2):設置模糊條件;
  • likeLeft(String s1, String s2):設置左模糊條件;
  • likeRight(String s1, String s2):設置右模糊條件。
@Test
void select() {
	// 模糊查詢
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.like("name", "小");       // %小%
	wrapper.likeLeft("name", "小");   // %小
	wrapper.likeRight("name", "小");  // 小%
	System.out.println(mapper.selectList(wrapper));
}

7、嵌套查詢

嵌套查詢 需要在 Wrapper 條件中設置嵌套條件,此方法是 Wrapper 的方法。

  • inSql(String name, String sql):設置嵌套條件。
@Test
void select() {
    // 嵌套查詢
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.inSql("id", "select id from user where id < 10");
	wrapper.inSql("age", "select age from user where age > 1");
    
	// 執行的 SQL 語句如下:
	// SELECT ... AND 
	// (id IN (select id from user where id < 10) 
	// AND age IN (select age from user where age > 1)) 
    
	System.out.println(mapper.selectList(wrapper));
}

8、排序查詢

排序查詢 需要在 Wrapper 條件中設置排序條件,此方法是 Wrapper 的方法。

  • orderByAsc(String name):設置升序排序的字段;
  • orderByDesc(String name):設置降序排序的字段。
@Test
void select() {
	// 排序查詢(asc升序,desc降序)
	QueryWrapper<User> wrapper = new QueryWrapper<>();
	wrapper.orderByAsc("age");  // 根據 age 進行升序排序
	System.out.println(mapper.selectList(wrapper));
}


六、自定義 SQL

如果 MP 中提供的方法無法應付你的需求,你也可以 自定義 SQL 語句。這裏以多表關聯查詢爲例:

1、準備工作

多表關聯查詢需要準備兩張表和 VO 實體類以及 Mapper。

1)數據表

create table `t_user` (
	`id` int(11) not null auto_increment,
	`name` varchar(255),
	`age` int(11),
	primary key (`id`)
);

create table `t_product` (
	`id` int(11) not null auto_increment,
	`description` varchar(255),
	`count` int(11),
	primary key (`id`)
);

-- 隨意插入幾條記錄

2)VO 實體類

這裏我用 VO 來封裝實體類。

@Data
public class ProductVO {
    @TableId
    private Integer id;
    private String description;
    private Integer count;
    private Integer userId;
    private String userName;
}

2、Mapper

public interface UserMapper extends BaseMapper<User> {
	@Select("select p.id, p.description, p.count, u.id user_id, u.`name` user_name from t_user u, t_product p where u.id = p.user_id and u.id = #{id}")
	List<ProductVO> productList(Integer id);
}


博客中若有不恰當的地方,請您一定要告訴我。前路崎嶇,望我們可以互相幫助,並肩前行!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章