• Mybatis-plus的使用


    接口mapper需要继承BaseMapper<要操作的类>外加@Mapper

    mport org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import java.util.List;
    @Mapper
    public interface AdminUserMapper extendsBaseMapper<AdminUserEntity> {
    
    AdminUserEntity:
    @TableName("openapi_admin_user")
    @Data
    public class AdminUserEntity extends BaseEntity {
        @TableId("user_id")
        private Long userId;
        private String userName;
        private String userPassword;
        private String userType;
        private String status;
        private String telephone;
        private String isInitPwd;
        private Long renterId;
    
        /**
         *  登录用户 及新增用户的创建人
         */
        private String createBy;

    BaseEntity:

    @Data
    @ApiModel("基础实体类")
    public abstract class BaseEntity {
    
        @ApiModelProperty(value = "创建人")
        private String createBy;
    
        @ApiModelProperty(value = "更新人")
        private String updateBy;
    
        @ApiModelProperty(value = "更新时间")
        @JsonSerialize(using = JsonDateSerializer.class)
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date dateUpdated;
    
        @ApiModelProperty(value = "创建时间")
        @JsonSerialize(using = JsonDateSerializer.class)
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date dateCreated;
    
    }

     1:如果有涉及到输入框的查询时,分页

    Controller:

    @ApiOperation("查询角色列表")
    @PostMapping("/list")
    public ResponseDto<Page<RoleResponse>> listRoles(@RequestBody @Valid PageWrapper<RoleRequest> pageRequest) {
        log.info("/roles/list start");
        log.info("【/roles/list】调用roleService层入参: " + pageRequest);
        Page page = new Page(pageRequest.getCurrent(), pageRequest.getSize());
        if(pageRequest.getDataBody() == null) {
            throw new ServiceException(ResponseCode.ValidationError.getCode(), "缺少参数dataBody");
        }
        Page<RoleResponse> list = roleService.selectRoleListByCondition(page, pageRequest.getDataBody());
        log.info("/roles/list end");
        return ResponseUtil.success(list);
    
    }

    PageWrapper:

     */
    @Data
    public class PageWrapper<T> {
        @NumberFormat
        private int current = 1;
        private int size = 10;
        private int total;
        private int pages;
    
        @Valid
        private T dataBody;
    }

    Repository:(无排序)

    */
    public Page<RoleResponse> selectRoleListByCondition(Page pageRequest, RoleRequest request) {
        List<RoleResponse> responseList = new ArrayList<>(0);
    
        Pagination page = getPageParam(pageRequest);
    
        // condition
        RoleEntity param = new RoleEntity();
        EntityWrapper<RoleEntity> wrapper = new EntityWrapper<>(param);
        wrapper.like(StringUtils.isNotBlank(request.getRoleName()), "aa.role_name", request.getRoleName());
        wrapper.ge(request.getStart() != null, "aa.date_created", request.getStart() + " 00:00:00");
       /* if (StringUtils.isNotEmpty(request.getEnd())) {
            wrapper.le("aa.date_updated", request.getEnd() + " 23:59:59");
        }*/
        wrapper.le(request.getEnd() != null,"aa.date_created", request.getEnd() + " 23:59:59");
        wrapper.eq(request.getRoleId() != null, "aa.role_id", request.getRoleId());
        log.info("selectRoleListByCondition:: {}", wrapper.getSqlSegment());
    
        List<RoleResponse> entities = null;
        try {
            // 查询角色列表
            entities = roleMapper.selectRolesByPage(page, wrapper);
            if (CollectionUtils.isEmpty(entities)) {
                log.warn("No roles were found.");
                return buildResponse(page, responseList);
            }


    private Page<RoleResponse> buildResponse(Pagination page, List<RoleResponse> responses) {
    Page<RoleResponse> result = new Page<>(page.getCurrent(), page.getSize());
    result.setRecords(responses);
    result.setTotal(page.getTotal());
    return result;
    }
     

    Repository(排序)

    public List<UserResponse> listUsers(UserRequest request) {
        AdminUserEntity userEntity = new AdminUserEntity();
        EntityWrapper<AdminUserEntity> ew = new EntityWrapper<>(userEntity);
        ew.eq("status", CommonFlagEnum.Yes.getCode()).eq(StringUtils.isNotBlank(request.getCompanyName()),
                "company_name", request.getCompanyName()).eq(StringUtils.isNotBlank(request.getUserType()),
                "user_type", request.getUserType()).eq(StringUtils.isNotBlank(request.getUserName()),
                "um_id", request.getUserName()).like(StringUtils.isNotBlank(request.getUserName()),
                "user_name", request.getUserName());
        //排序列
        List<String> orderColumns = new ArrayList<>();
        orderColumns.add("date_created");
    
        ew.orderDesc(orderColumns);
        log.info("sql: {}, {}", ew.getSqlSelect(), ew.getSqlSegment());
    
        try {
            List<AdminUserEntity> entities = userMapper.selectList(ew);

    Mapper:

          

    List<RoleResponse> selectRolesByPage(Pagination pagination, @Param("ew") Wrapper<RoleEntity> wrapper);

    xml:

    <select id="selectRolesByPage" resultType="com.paic.ocss.gateway.model.dto.role.RoleResponse">
        SELECT
        aa.role_id,
        aa.role_name,
        aa.STATUS,
        aa.date_created,
        aa.create_by,
        aa.date_updated,
        aa.update_by,
        aa.role_desc,
        bb.resource_ids
        FROM
        openapi_admin_role aa
        LEFT JOIN ( SELECT GROUP_CONCAT( r.resource_id ) resource_ids, r.role_id FROM
        openapi_admin_role_resource_mapping r GROUP BY r.role_id ) bb ON aa.role_id = bb.role_id
        <where>
            ${ew.sqlSegment}
        </where>
        order by date_created desc
    
    </select>

    2:如果没有涉及到输入框的查询时,分页,而是简单的增,删,改,查:

    public void modify(UserModify userRequest) {
    
        AdminUserEntity userEntity = new AdminUserEntity();
        userEntity.setUserId(userRequest.getUserId());
        if (StringUtils.isNotBlank(userRequest.getTelephone())) {
            userEntity.setTelephone(userRequest.getTelephone());
        }
        if (StringUtils.isNotBlank(userRequest.getUserName())) {
            userEntity.setUserName(userRequest.getUserName());
        }
        if (StringUtils.isNotBlank(userRequest.getStatus())) {
            userEntity.setStatus(userRequest.getStatus());
        }
        if (userRequest.getRenterId() != null) {
            userEntity.setRenterId(userRequest.getRenterId());
        }
    
        String loginAccount = SecurityUtils.getSubject().getPrincipal().toString();
        userEntity.setUpdateBy(loginAccount);
    
        if (CommonFlagEnum.Yes.getCode().equals(userRequest.getIsInitPwd())) {
            //存储到db的密码
            userEntity.setUserPassword(SHA256Util.getSHA256StrJava(DEFAULT_PASSWORD));
        } else if(userRequest.getUserPassword() != null){
            userEntity.setUserPassword(SHA256Util.getSHA256StrJava(userRequest.getUserPassword()));
        }
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        //userEntity.setDateUpdated(format.format(new Date()));
        userEntity.setDateUpdated(new Date());
    
        try {
            int count = userMapper.updateById(userEntity);

  • 相关阅读:
    HLJU 1221: 高考签到题 (三分求极值)
    [视频解说]Java(JDK的下载安装及第一个程序执行)
    llvm中如何利用分支概率和基本块频率估计
    Nginx SSL TLS部署最佳实践
    Nginx使用教程(一):Nginx编译参数详解
    Nginx使用教程(一):下载并编译安装Nginx
    nginx使用ssl模块配置HTTPS支持
    Linux下安装Tomcat服务器和部署Web应用
    TOMCAT-报错The BASEDIR environment variable is not defined correctly
    Kafka vs RocketMQ——多Topic对性能稳定性的影响-转自阿里中间件
  • 原文地址:https://www.cnblogs.com/leeego-123/p/10831768.html
Copyright © 2020-2023  润新知