コンテンツ
6.非単一テーブルクエリおよびその他の操作用にSQLを(xml構成を使用して)カスタマイズします
1、BaseMapper
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.baomidou.mybatisplus.core.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
* @param entity 实体对象
* @return
*/
int insert(T entity);
/**
* 根据ID删除
* @param id 主键id
* @return
*/
int deleteById(Serializable id);
/**
* 根据实体ID删除
* @param entity 实体对象
* @return
*/
int deleteById(T entity);
/**
* 根据columnMap条件删除记录
* @param columnMap 表字段map对象
* @return
*/
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
/**
* 根据entity条件删除记录
* @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
* @return
*/
int delete(@Param("ew") Wrapper<T> queryWrapper);
/**
* 删除(根据ID 批量删除)
* @param idList 主键ID列表(不能为 null 以及 empty)
* @return
*/
int deleteBatchIds(@Param("coll") Collection<?> idList);
/**
* 根据 ID 修改,不会修改没有使用 set 注入属性的属性值
* @param entity 实体对象
* @return
*/
int updateById(@Param("et") T entity);
/**
* 根据 whereEntity 条件,更新记录
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
* @return
*/
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
* @param id 主键ID
* @return
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
* @param idList 主键ID列表(不能为 null 以及 empty)
* @return
*/
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
* @param columnMap 表字段 map 对象
* @return
*/
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
* 查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常
* @param queryWrapper 实体对象封装操作类(可以为 null)
* @return
*/
default T selectOne(@Param("ew") Wrapper<T> queryWrapper) {
List<T> ts = this.selectList(queryWrapper);
if (CollectionUtils.isNotEmpty(ts)) {
if (ts.size() != 1) {
throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records", new Object[0]);
} else {
return ts.get(0);
}
} else {
return null;
}
}
/**
* 根据 Wrapper 条件,查询总记录数
* @param queryWrapper 实体对象封装操作类(可以为 null)
* @return
*/
default boolean exists(Wrapper<T> queryWrapper) {
Long count = this.selectCount(queryWrapper);
return null != count && count > 0L;
}
/**
* 根据 Wrapper 条件,查询总记录数
* @param queryWrapper 实体对象封装操作类(可以为 null)
* @return
*/
Long selectCount(@Param("ew") Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
* @param queryWrapper 实体对象封装操作类(可以为 null)
* @return
*/
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* @param queryWrapper 实体对象封装操作类(可以为 null)
* @return
*/
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* 注意: 只返回第一个字段的值
* @param queryWrapper 实体对象封装操作类(可以为 null)
* @return
*/
List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录(并翻页)
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
* @param <P>
* @return
*/
<P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录(并翻页)
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
* @param <P>
* @return
*/
<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);
}
2.挿入
@Test
public void testInsert(){
User user = new User();
user.setName("王五");
user.setAge(46);
user.setEmail("[email protected]");
//
int result = userMapper.insert(user);
System.out.println("result = " + result);
System.out.println("id = " + user.getId()); //这里获取的id是mybatis-plus通过雪花算法得到的
}
3.削除
@Test
public void testDelete(){
// 通过id删除用户信息
// DELETE FROM user WHERE id=?
/*int result = userMapper.deleteById(1512743678382899202L);
System.out.println("result = " + result);*/
// 根据map集合中所设置的条件删除用户信息
/*Map<String, Object> map = new HashMap<>();
map.put("name", "王五");
map.put("age", "46");
// DELETE FROM user WHERE name = ? AND age = ?
int result = userMapper.deleteByMap(map);
System.out.println("result = " + result);*/
// 通过多个ID实现批量删除
List<Long> list = Arrays.asList(1512743901935067138L, 0L);
// DELETE FROM user WHERE id IN ( ? , ? )
int result = userMapper.deleteBatchIds(list);
System.out.println("result = " + result);
}
4.変更
@Test
public void testUpdate(){
User user = new User();
user.setId(1L);
user.setName("李四");
user.setEmail("[email protected]");
// UPDATE user SET name=?, email=? WHERE id=?
// 不会修改没有set的属性值
int result = userMapper.updateById(user);
System.out.println("result = " + result);
}
5.クエリ
@Test
public void testSelect(){
// 通过ID查询用户信息
/*// SELECT id,name,age,email FROM user WHERE id=?
User user = userMapper.selectById(1L);
System.out.println(user);*/
// 根据多个ID查询多个用户信息
/*List<Long> list = Arrays.asList(1L, 2L, 3L);
// SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
List<User> users = userMapper.selectBatchIds(list);
users.forEach(System.out::println);*/
// 根据Map集合中的条件查询用户信息
/*Map<String, Object> map = new HashMap<>();
map.put("name", "Jack");
map.put("age", 20);
// SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);*/
// 查询所有数据
// SELECT id,name,age,email FROM user
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
6.非単一テーブルクエリおよびその他の操作用にSQLを(xml構成を使用して)カスタマイズします
mybatis-plusでデフォルトで読み取られるXxxMapper.xmlの場所は、src / main / resources / mapper(任意のレイヤーディレクトリを含むことができます)の下のすべてのxmlファイルであるため、XxxMapper.xmlの場所を次のように設定する必要はありません。私たち自身
マッパーインターフェイス:UserMapper
@Mapper
//@Repository //将该类或接口标识为持久层组件
public interface UserMapper extends BaseMapper<User> {
/**
* 根据id查询用户信息为map集合
* @param id
* @return
*/
Map<String, Object> selectMapById(Long id);
}
構成ファイル:UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zyj.mybatisplus.mapper.UserMapper">
<!-- Map<String, Object> selectMapById(Long id); -->
<select id="selectMapById" resultType="map">
select id,name,age,email from user where id = #{id}
</select>
</mapper>
試験方法:
@Test
public void testSelectMapById(){
Map<String, Object> map = userMapper.selectMapById(1L);
System.out.println(map);
}
出力結果:
==> Preparing: select id,name,age,email from user where id = ?
==> Parameters: 1(Long)
<== Columns: id, name, age, email
<== Row: 1, 李四, 18, [email protected]
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@65753040]
{name=李四, id=1, age=18, [email protected]}
7、通用 Service
説明:
General Service CRUD IServiceインターフェイスをカプセル化し、CRUDをさらにカプセル化します。getを使用して単一行をクエリします。削除リストを削除します。クエリコレクションページページングプレフィックスの命名方法で、混乱を避けるためにMapperレイヤーを区別します。
ジェネリックTは任意のエンティティオブジェクトです
一般的なServiceメソッドをカスタマイズする可能性がある場合は、Mybatis-Plusが提供する基本クラスを継承する独自のIBaseServiceを作成することをお勧めします。
公式ウェブサイトアドレス:CRUDインターフェース| MyBatis-Plus
7.1、IService
MyBatis-Plusには、インターフェイスIServiceとその実装クラスServiceImplがあり、一般的なビジネスレイヤーロジックをカプセル化します。詳細については、ソースコードIServiceおよびServiceImplを参照してください(中国語で記述されているため、内部のコメントは中国語であるため)
7.2.サービスインターフェイスとその実装クラスを作成する
public interface UserService extends IService<User> {
}
@Service
// ServiceImpl<mapper接口, 实体类>
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
7.3.テストクエリレコードの数
試験方法:
public class MyBatisPlusServiceTest {
@Autowired
private UserService userService;
@Test
public void testGetCount(){
// 查询总记录数
// SELECT COUNT( * ) FROM user
long count = userService.count();
System.out.println("总记录数 = " + count);
}
}
出力結果:
==> Preparing: SELECT COUNT( * ) FROM user
==> Parameters:
<== Columns: COUNT( * )
<== Row: 5
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@238bfd6c]
总记录数 = 5
7.4.テストバッチの追加
試験方法:
@Test
public void testInsertMore(){
// 批量添加
// Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
List<User> list = new ArrayList<>();
for(int i = 0; i < 10; i++){
User user = new User();
user.setName("张" + i);
user.setAge(20 + i);
user.setEmail("zhang" + i + "@qq.com");
list.add(user);
}
boolean b = userService.saveBatch(list);
System.out.println(b);
}
出力結果:
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1513090537404141570(Long), 张0(String), 20(Integer), [email protected](String)
==> Parameters: 1513090537634828289(Long), 张1(String), 21(Integer), [email protected](String)
==> Parameters: 1513090537634828290(Long), 张2(String), 22(Integer), [email protected](String)
==> Parameters: 1513090537634828291(Long), 张3(String), 23(Integer), [email protected](String)
==> Parameters: 1513090537634828292(Long), 张4(String), 24(Integer), [email protected](String)
==> Parameters: 1513090537634828293(Long), 张5(String), 25(Integer), [email protected](String)
==> Parameters: 1513090537634828294(Long), 张6(String), 26(Integer), [email protected](String)
==> Parameters: 1513090537634828295(Long), 张7(String), 27(Integer), [email protected](String)
==> Parameters: 1513090537634828296(Long), 张8(String), 28(Integer), [email protected](String)
==> Parameters: 1513090537634828297(Long), 张9(String), 29(Integer), [email protected](String)
true