Mybatis-plus是在Mybatis的基础上做增强,为简化开发而生
- 只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑。
- 只需简单配置,即可快速进行 CRUD 操作,从而节省大量时间。
- 热加载、代码生成、分页、性能分析等功能一应俱全。
官网文档
CREATE TABLE `t_hero` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`neck_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`create_time` datetime(0) NULL DEFAULT NULL,
`update_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.3.2version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<dpendency>
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
global-config:
db-config:
id-type: auto
table-prefix: t_
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@Data
public class Hero {
private int id;
private String name;
private String neckName;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
@Component
public interface HeroMapper extends BaseMapper<Hero> {
}
//添加操作,参数是一个实体类
int insert(T entity);
//测试
@Test
void testInsert(){
int insert = heroMapper.insert(new Hero("史蒂夫", "美国队长"));
System.out.println("添加的数据条数:"+insert);
}
//SQL日志
/* ==> Preparing: INSERT INTO t_hero ( name, neck_name, create_time, update_time ) VALUES ( ?, ?, ?, ? )
==> Parameters: 史蒂夫(String), 美国队长(String), 2020-07-29 10:39:24.823(Timestamp), 2020-07-29 10:39:24.823(Timestamp)
<== Updates: 1
*/
// 根据自定义条件构造删除
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
//根据ID 批量删除,参数为list
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据map删除,传入值为map,map的key对应表中的字段
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
//测试
@Test
void testDeleteBatchIds(){
int i = heroMapper.deleteBatchIds(Arrays.asList(new Integer[]{1, 2, 3}));
System.out.println("删除的数据条数:"+i);
}
/**
* ==> Preparing: DELETE FROM t_hero WHERE id IN ( ? , ? , ? )
* ==> Parameters: 1(Integer), 2(Integer), 3(Integer)
* <== Updates: 3
*/
@Test
void testDelete(){
QueryWrapper<Hero> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("id",1)
.likeLeft("neck_name","战士");
heroMapper.delete(queryWrapper);
}
/**
* ==> Preparing: DELETE FROM t_hero WHERE (id > ? AND neck_name LIKE ?)
* ==> Parameters: 1(Integer), %战士(String)
* <== Updates: 1
*/
// 根据id更新,参数为实体类,只更新不为空的属性(字段)
int updateById(@Param(Constants.ENTITY) T entity);
//测试
@Test
void testUpdateById(){
Hero hero = new Hero(1,"Tony");
heroMapper.updateById(hero);
}
/**
* ==> Preparing: UPDATE t_hero SET name=?, update_time=? WHERE id=?
* ==> Parameters: Tony(String), 2020-07-29 11:00:07.754(Timestamp), 1(Integer)
* <== Updates: 1
*/
// 根据 wrapper 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 wrapper 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
//测试
@Test
void testSelectList(){
List<Hero> list = heroMapper.selectList(new QueryWrapper<Hero>().gt("id", 1));
list.forEach(hero -> System.out.println(hero));
}
/**
* ==> Preparing: SELECT id,name,neck_name,create_time,update_time FROM t_hero WHERE (id > ?)
* ==> Parameters: 1(Integer)
* <== Columns: id, name, neck_name, create_time, update_time
* <== Row: 4, 史蒂夫, 美国队长, 2020-07-29 02:39:25, 2020-07-29 02:39:25
* <== Row: 5, Thor, 雷神, 2020-07-16 11:08:54, 2020-07-31 11:08:56
* <== Row: 6, Loki, 洛基, 2020-07-23 11:09:18, 2020-07-30 11:09:21
* <== Total: 3
*/
@Test
void testSelectCount(){
Integer count = heroMapper.selectCount(new QueryWrapper<Hero>().gt("id", 1));
System.out.println("数据总数:"+count);
}
/**
* ==> Preparing: SELECT COUNT( 1 ) FROM t_hero WHERE (id > ?)
* ==> Parameters: 1(Integer)
* <== Columns: COUNT( 1 )
* <== Row: 3
* <== Total: 1
*/
@Test
void testSelectOne(){
QueryWrapper<Hero> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id",1)
.eq("name","Tony");
Hero hero = heroMapper.selectOne(queryWrapper);
}
/**
* ==> Preparing: SELECT id,name,neck_name,create_time,update_time FROM t_hero WHERE (id = ? AND name = ?)
* ==> Parameters: 1(Integer), Tony(String)
* <== Columns: id, name, neck_name, create_time, update_time
* <== Row: 1, Tony, 钢铁侠, 2020-07-16 10:51:38, 2020-07-29 03:00:08
* <== Total: 1
*/
@Test
void testSelectPage(){
//limit 0,2 ,分页插件配置参考下文
IPage<Hero> page = new Page<>(0,2);
IPage<Hero> data = heroMapper.selectPage(page, new QueryWrapper<Hero>().lt("id",10));
data.getRecords().forEach(hero -> System.out.println(hero));
}
/**
==> Preparing: SELECT id,name,neck_name,create_time,update_time FROM t_hero WHERE (id < ?) LIMIT ?,?
==> Parameters: 10(Integer), 0(Long), 2(Long)
*/
@Test
void testSelectByMap(){
Map<String,Object> map= new HashMap<>();
map.put("id",1);
map.put("name","Thor");
List<Hero> list = heroMapper.selectByMap(map);
}
/**
* ==> Preparing: SELECT id,name,neck_name,create_time,update_time FROM t_hero WHERE name = ? AND id = ?
* ==> Parameters: Thor(String), 1(Integer)
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
//设置fill为FieldFill枚举类型
//共四种类型:DEFAULT,INSERT,UPDATE,INSERT_UPDATE;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
/**
* 添加时间自动填充配置
* insertFill() : 插入时
* updateFill() : 更新时
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}