Mybatis-plus的使用
阅读原文时间:2023年07月15日阅读:3

接口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:

@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> listRoles(@RequestBody @Valid PageWrapper 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 list = roleService.selectRoleListByCondition(page, pageRequest.getDataBody());
log.info("/roles/list end");
return ResponseUtil.success(list);

}

PageWrapper:

*/
@Data
public class PageWrapper {
@NumberFormat
private int current = 1;
private int size = 10;
private int total;
private int pages;

@Valid  
private T dataBody;  

}

Repository:(无排序)

*/
public Page selectRoleListByCondition(Page pageRequest, RoleRequest request) {
List 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 buildResponse(Pagination page, List responses) {
Page result = new Page<>(page.getCurrent(), page.getSize());
result.setRecords(responses);
result.setTotal(page.getTotal());
return result;
}

Repository(排序)

public List listUsers(UserRequest request) {
AdminUserEntity userEntity = new AdminUserEntity();
EntityWrapper 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 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 selectRolesByPage(Pagination pagination, @Param("ew") Wrapper wrapper);

xml:

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);