序文
Spring Bootシリーズ:クリックしてSpringBootシリーズの記事を表示します
MyBatis-Plus
MyBatis-Plus(略してMP)は、MyBatisの拡張ツールであり、MyBatisに基づいて、拡張するだけで変更はありません。開発を簡素化し、効率を向上させるために生まれました。
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD
操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD
操作 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller
层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持
MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
フレームワーク
MyBatis-Plusの簡単な紹介、そしてMyBatis-Plusの統合を開始します
SpringBootはMyBatis-Plusを統合します
1.依存関係を追加します
MyBatis-Plus3.0バージョンはJDK8に基づいています
Mybatis-plusは以下に依存します。最新バージョンは3.4.1です。バージョンは自分で選択できます。
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 数据库驱动 ,根据自己的数据库选择对应的驱动,我这里是mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
以下は、MPが依存するバージョン情報です。
注:mybatisとmybatis-plusの依存関係を同時にインポートしないようにしてください!予測できない問題を引き起こすバージョンの違いを避けてください。
2.データベース接続を構成します
次のように、application.propertiesにデータベースの構成を追加します。
#数据库url
spring.datasource.url=jdbc:mysql://192.168.91.128:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
# 驱动版本不同,对应的driver-class-name不同
# mysql 5 com.mysql.jdbc.Driver
# mysql 8 com.mysql.cj.jdbc.Driver、在datasource.url需要增加时区的配置serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
#数据库用户名
spring.datasource.username=root
#密码
spring.datasource.password=root
次の構成は、実行されたsqlステートメントをコンソールに出力するためのものです。コンソールにsqlを出力する場合は、テストを容易にするために次の構成を追加できます。
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3. @ MapperScanアノテーションをSpringBootスタートアップクラスに追加して、Mapperフォルダーをスキャンします
@SpringBootApplication
@MapperScan("com.example.spring_cloud_demo.mapper")
public class SpringCloudDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudDemoApplication.class, args);
}
}
上記の設定の後、MPを使用できます。実際、設定は基本的にmybatisの設定と同じであることがわかります。これは、MPが元々mybatisに基づいて拡張されているためです。これは、mybatisの機能を保持し、 mybatisで使用されます。より強化された機能を提供します
MyBatis-PlusのCRUD
以下に、MyBatis-Plusの単純なクラッド機能を示します。
1.エンティティクラスを作成します
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
2.マッパーインターフェイスを作成します。マッパーインターフェイスはBaseMapperを継承します。マッパーがBaseMapperインターフェイスを継承した後、mapper.xmlファイル、つまりBaseMapperで定義されたメソッドを記述せずにCRUD関数を取得できます。
以下は私自身のマッパーです
@Repository
public interface UserMapper extends BaseMapper<User> {
@Select("select * from user where id=#{id}")
List<User>getUserList(@Param("id")Integer id);
}
注:mybatis-plusはmybatisの機能をサポートしているため、アノテーションsqlファイルとxmlファイルを使用することもできます
ちなみにmybatis-plusは中国語で書かれているので、ソースコードのコメントも中国語でとてもフレンドリーです
BaseMapper源码如下:
/**
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
* <p>这个 Mapper 支持 id 泛型</p>
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* <p>注意: 只返回第一个字段的值</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
<E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
BaseMapperの継承に加えて、MPでは、ServiceImplを継承することで基本的なCRUD関数を取得することもできます。ServiceImplは次のように定義されています。
/**
* IService 实现类( 泛型:M 是 mapper 对象,T 是实体 )
*
* @author hubin
* @since 2018-06-23
*/
@SuppressWarnings("unchecked")
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
}
成し遂げる
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> {
}
注:ServiceImplの2つのジェネリック型。MはBaseMapperを継承するクラスを表し、Tはエンティティクラスを表します。
テスト
次に、BaseMapperの機能をテストします
@SpringBootTest
class SpringCloudDemoApplicationTests {
private static Pattern linePattern = Pattern.compile("_(\\w)");
@Autowired
private UserMapper userMapper;
@Test
public void testMP() {
//插入
User newUser = User.builder().id(3L).name("新增用户").age(22).email("666").build();
userMapper.insert(newUser);
//selectList() 方法的参数为 MP 内置的条件封装器 Wrapper,为null则表示没有条件,查询全部
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
//根据id查询
User user = userMapper.selectById(2);
//更新
user.setName("hh");
userMapper.updateById(user);
System.out.println("-----------------------------");
//QueryWrapper为对象封装操作类,主要用于构造查询条件
QueryWrapper queryWrapper=new QueryWrapper();
//ge方法用于构造大于等于条件,下面语句等于id>=2
queryWrapper.ge(true,"id",2);
List<User> userListByWrapper = userMapper.selectList(queryWrapper);
userListByWrapper.forEach(System.out::println);
}
}
MyBatis-Plusの統合はとてもシンプルなので、より多くの操作が後で詳細に紹介されます