MyBatis-Plus官网
MyBatis-Plus的使用 依赖同学,在使用MyBatis-plus之前,记住一句话:单表查询使用MyBatis-Plus,多表查询使用MyBatis。
因为,这样做,才能使代码更加简单,以及帮助自己快速开发。
我这里使用的版本是
3.2.0
一张用户表com.baomidou mybatis-plus-boot-starter${mybatis-plus.version}
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROp TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `uuid` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `image_path` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `create_date` timestamp NOT NULL, `update_date` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `is_deleted` tinyint(1) NULL DEFAULT 1 COMMENT '逻辑删除位,1表示可用,0表示删除', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;Java用户实体类
package cn.ant.uc.entity.po; import com.baomidou.mybatisplus.annotation.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor @TableName("user") public class User { //自增id @TableId(value = "id",type = IdType.AUTO) private Integer id; @TableField(value = "uuid") private String uuid; @TableField(value = "username") private String username; @TableField(value = "password") private String password; @TableField("image_path") private String imagePath; @TableField(value = "create_date",fill = FieldFill.INSERT) private Date createDate; @TableField(value = "update_date",fill = FieldFill.UPDATE) private Date updateDate; //逻辑删除 @TableLogic private Boolean isDeleted; }Mybati-plus的配置
mybatis-plus: mapper-locations: classpath*:/mapper*.xml type-aliases-package: cn.ant.*.entity.* global-config: db-config: id-type: auto #id自增 logic-delete-value: 0 #逻辑删除,设置为0 logic-not-delete-value: 1 #不删除,设置为1 banner: false configuration: map-underscore-to-camel-case: true cache-enabled: false call-setters-on-nulls: true jdbc-type-for-null: 'null'注意事项
注意1:正常情况下,如上面的配置,就可以使用mybatis-plus了。
但是,细心的同学会发现上面的实体类,@TableField注解标记时间字段(createDate和updateDate)的时候,配置了fill = FieldFill.INSERT和fill = FieldFill.UPDATE。如果想要这样的配置生效,还需要写一个mybatis-plus的自动填充配置类。
mybatis-plus自动填充配置类注意2:如果想使用mybatis-plus的分页方法(如selectPage等),还需要配置一个分页插件配置类。否则,mybatis-plus分页方法不生效。
package cn.ant.common.config; import com.baomidou.mybatisplus.core.handlers.metaObjectHandler; import org.apache.ibatis.reflection.metaObject; import org.springframework.context.annotation.Configuration; import java.util.Date; @Configuration public class MybatisPlusFieldFillConfigure implements metaObjectHandler { @Override public void insertFill(metaObject metaObject) { this.setInsertFieldValByName("createDate",new Date(),metaObject); this.setUpdateFieldValByName("updateDate",new Date(),metaObject); } @Override public void updateFill(metaObject metaObject) { this.setUpdateFieldValByName("updateDate",new Date(),metaObject); } }分页插件配置类
使用该配置类之前,使用mybatis-plus的selectPage方法,
它的sql是:
SELECT id,update_date,password,is_deleted,image_path,uuid,create_date,username FROM user WHERe is_deleted=1
使用该配置类之后,使用mybatis-plus的selectPage方法,
它的sql是:
SELECT id,update_date,password,is_deleted,image_path,uuid,create_date,username FROM user WHERe is_deleted=1 LIMIT 0,10
package cn.ant.common.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyBatisPlusPageInterceptor { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); //优化处理类 paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true)); return paginationInterceptor; } }mybatis-plus的基本使用
mapper只需要集成mybatisPlus的baseMapper即可,泛型类是与数据表对应的实体类,如下:
package cn.ant.uc.mapper; import cn.ant.uc.entity.po.User; import com.baomidou.mybatisplus.core.mapper.baseMapper; import org.springframework.stereotype.Repository; @Repository public interface UserManagementMapper extends baseMapperMyBatis-Plus的CRUD DTO类{ }
dto是前后端交互的实体类
package cn.ant.uc.entity.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @AllArgsConstructor @NoArgsConstructor @ApiModel(value = "用户DTO") public class UserDTO implements Serializable { @ApiModelProperty(value = "用户id") private Integer id; @ApiModelProperty(value = "用户名") private String username; @ApiModelProperty(value = "用户密码") private String password; @ApiModelProperty(value = "t头像路径") private String imagePath; @ApiModelProperty(value = "当前页索引值,默认1") private Integer pageIndex = 1; @ApiModelProperty(value = "每一页大小,默认10") private Integer pageSize = 10; @ApiModelProperty(value = "排序标记,默认true升序") private Boolean orderByFlag = true; }接口
public Object addUser(UserDTO userDTO); public Object editUser(UserDTO userDTO); public Object queryUser(UserDTO userDTO); public Object deleteUser(List接口实现类userIdList);
@Override public Object addUser(UserDTO userDTO) { //复制对象值 User user = new User(); BeanUtils.copyProperties(userDTO, user); //密码加密 user.setPassword(SecureUtil.md5(userDTO.getPassword())); //生成UUId user.setUuid(UUID.randomUUID().toString()); //添加数据 Integer insert = userManagementMapper.insert(user); return insert; } @Override public Object editUser(UserDTO userDTO) { //构建更新条件以及字段 LambdaUpdateWrapperuserLambdaUpdateWrapper = new UpdateWrapper ().lambda(); //用户名不为空 if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getUsername())) { userLambdaUpdateWrapper.set(User::getUsername, userDTO.getUsername()); } //密码不为空 if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getPassword())) { userLambdaUpdateWrapper.set(User::getPassword, userDTO.getPassword()); } //头像路径不为空 if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getImagePath())) { userLambdaUpdateWrapper.set(User::getImagePath, userDTO.getImagePath()); } //选择条件 userLambdaUpdateWrapper.eq(User::getId, userDTO.getId()); int update = userManagementMapper.update(null, userLambdaUpdateWrapper); return update; } @Override public Object queryUser(UserDTO userDTO) { //构造查询条件 LambdaQueryWrapper userLambdaQueryWrapper = new QueryWrapper ().lambda(); //用户名不为空 if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getUsername())) { userLambdaQueryWrapper.like(User::getUsername, userDTO.getUsername()); } //密码不为空 if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getPassword())) { userLambdaQueryWrapper.like(User::getPassword, userDTO.getPassword()); } //Id if (!Objects.isNull(userDTO) && !Objects.isNull(userDTO.getId())) { userLambdaQueryWrapper.like(User::getId, userDTO.getId()); } //分页查询 Page userPage = new Page<>(); userPage.setCurrent(userDTO.getPageIndex()); userPage.setSize(userDTO.getPageSize()); IPage userIPage = userManagementMapper.selectPage(userPage, userLambdaQueryWrapper); //密码防止泄露 ArrayList users = new ArrayList<>(); List userIPageRecords = userIPage.getRecords(); for (User userIPageRecord : userIPageRecords) { String password = DesensitizedUtil.password(userIPageRecord.getPassword()); userIPageRecord.setPassword(password); users.add(userIPageRecord); } return users; } @Override public Object deleteUser(List userIdList) { return userManagementMapper.deleteBatchIds(userIdList); }
好了,myabtis-plus的基本使用就是这样啦,我这里并没有详细介绍Mybatis-Plus的每个方法的使用,如果需要了解更多可以自行百度或者持续关注,我后面再更新。还有就是实际开发中,也差不多是这样使用。如果,在实际开发中,遇到多表查询,你要好不犹如的写上mybatis的xml配置,默默的去写sql吧。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)