Java Code Examples for com.baomidou.mybatisplus.core.conditions.query.QueryWrapper#and()

The following examples show how to use com.baomidou.mybatisplus.core.conditions.query.QueryWrapper#and() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DictService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查询分页数据,Specification模式
 *
 * @author stylefeng
 * @Date 2019-03-13
 */
public LayuiPageInfo findPageBySpec(DictParam param) {
    QueryWrapper<Dict> objectQueryWrapper = new QueryWrapper<>();
    objectQueryWrapper.eq("dict_type_id", param.getDictTypeId());

    if (ToolUtil.isNotEmpty(param.getCondition())) {
        objectQueryWrapper.and(i -> i.eq("code", param.getCondition()).or().eq("name", param.getCondition()));
    }

    objectQueryWrapper.orderByAsc("sort");

    List<Dict> list = this.list(objectQueryWrapper);

    //创建根节点
    Dict dict = new Dict();
    dict.setName("根节点");
    dict.setDictId(0L);
    dict.setParentId(-999L);
    list.add(dict);

    LayuiPageInfo result = new LayuiPageInfo();
    result.setData(list);

    return result;
}
 
Example 2
Source File: DictTypeService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查询分页数据,Specification模式
 *
 * @author stylefeng
 * @Date 2019-03-13
 */
public LayuiPageInfo findPageBySpec(DictTypeParam param) {
    Page pageContext = getPageContext();
    QueryWrapper<DictType> objectQueryWrapper = new QueryWrapper<>();
    if (ToolUtil.isNotEmpty(param.getCondition())) {
        objectQueryWrapper.and(i -> i.eq("code", param.getCondition()).or().eq("name", param.getCondition()));
    }
    if (ToolUtil.isNotEmpty(param.getStatus())) {
        objectQueryWrapper.and(i -> i.eq("status", param.getStatus()));
    }
    if (ToolUtil.isNotEmpty(param.getSystemFlag())) {
        objectQueryWrapper.and(i -> i.eq("system_flag", param.getSystemFlag()));
    }

    pageContext.setAsc("sort");

    IPage page = this.page(pageContext, objectQueryWrapper);
    return LayuiPageFactory.createPageInfo(page);
}
 
Example 3
Source File: QueryGenerator.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
/**
  * 根据权限相关配置 组装mp需要的权限
 * @param queryWrapper
 * @param clazz
 * @return
 */
public static void installAuthMplus(QueryWrapper<?> queryWrapper,Class<?> clazz) {
	//权限查询
	Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
		}
	}
	String name;
	for (int i = 0; i < origDescriptors.length; i++) {
		name = origDescriptors[i].getName();
		if (judgedIsUselessField(name)) {
			continue;
		}
		if(ruleMap.containsKey(name)) {
			addRuleToQueryWrapper(ruleMap.get(name), name, origDescriptors[i].getPropertyType(), queryWrapper);
		}
	}
}
 
Example 4
Source File: RestDictService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查询分页数据,Specification模式
 *
 * @author stylefeng
 * @Date 2019-03-13
 */
public LayuiPageInfo findPageBySpec(DictParam param) {
    QueryWrapper<RestDict> objectQueryWrapper = new QueryWrapper<>();
    objectQueryWrapper.eq("dict_type_id", param.getDictTypeId());

    if (ToolUtil.isNotEmpty(param.getCondition())) {
        objectQueryWrapper.and(i -> i.eq("code", param.getCondition()).or().eq("name", param.getCondition()));
    }

    objectQueryWrapper.orderByAsc("sort");

    List<RestDict> list = this.list(objectQueryWrapper);

    //创建根节点
    RestDict dict = new RestDict();
    dict.setName("根节点");
    dict.setDictId(0L);
    dict.setParentId(-999L);
    list.add(dict);

    LayuiPageInfo result = new LayuiPageInfo();
    result.setData(list);

    return result;
}
 
Example 5
Source File: QueryGenerator.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
/**
  * 根据权限相关配置 组装mp需要的权限
 * @param searchObj
 * @param parameterMap
 * @return
 */
public static void installAuthMplus(QueryWrapper<?> queryWrapper,Class<?> clazz) {
	//权限查询
	Map<String,SysPermissionDataRule> ruleMap = getRuleMap();
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
		}
	}
	String name;
	for (int i = 0; i < origDescriptors.length; i++) {
		name = origDescriptors[i].getName();
		if (judgedIsUselessField(name)) {
			continue;
		}
		if(ruleMap.containsKey(name)) {
			addRuleToQueryWrapper(ruleMap.get(name), name, origDescriptors[i].getPropertyType(), queryWrapper);
		}
	}
}
 
Example 6
Source File: RestDictTypeService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查询分页数据,Specification模式
 *
 * @author stylefeng
 * @Date 2019-03-13
 */
public LayuiPageInfo findPageBySpec(DictTypeParam param) {
    Page pageContext = getPageContext();
    QueryWrapper<RestDictType> objectQueryWrapper = new QueryWrapper<>();
    if (ToolUtil.isNotEmpty(param.getCondition())) {
        objectQueryWrapper.and(i -> i.eq("code", param.getCondition()).or().eq("name", param.getCondition()));
    }
    if (ToolUtil.isNotEmpty(param.getStatus())) {
        objectQueryWrapper.and(i -> i.eq("status", param.getStatus()));
    }
    if (ToolUtil.isNotEmpty(param.getSystemFlag())) {
        objectQueryWrapper.and(i -> i.eq("system_flag", param.getSystemFlag()));
    }

    pageContext.setAsc("sort");

    IPage page = this.page(pageContext, objectQueryWrapper);
    return LayuiPageFactory.createPageInfo(page);
}
 
Example 7
Source File: QueryGenerator.java    From teaching with Apache License 2.0 6 votes vote down vote up
/**
  * 根据权限相关配置 组装mp需要的权限
 * @param searchObj
 * @param parameterMap
 * @return
 */
public static void installAuthMplus(QueryWrapper<?> queryWrapper,Class<?> clazz) {
	//权限查询
	Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
		}
	}
	String name;
	for (int i = 0; i < origDescriptors.length; i++) {
		name = origDescriptors[i].getName();
		if (judgedIsUselessField(name)) {
			continue;
		}
		if(ruleMap.containsKey(name)) {
			addRuleToQueryWrapper(ruleMap.get(name), name, origDescriptors[i].getPropertyType(), queryWrapper);
		}
	}
}
 
Example 8
Source File: SmsRecordServiceImpl.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
public PageVo selectSmsRecordPageList(SmsRecordDTO smsRecordDTO) {
    QueryWrapper<SmsRecord> wrapper = new QueryWrapper(smsRecordDTO);
    wrapper.like(ObjectUtils.isNotEmpty(smsRecordDTO.getUserName()), "t3.name", smsRecordDTO.getUserName())
            .ge(ObjectUtils.isNotEmpty(smsRecordDTO.getStartTime()), "t.push_time", smsRecordDTO.getStartTime())
            .le(ObjectUtils.isNotEmpty(smsRecordDTO.getEndTime()), "t.push_time", smsRecordDTO.getEndTime())
            .eq(ObjectUtils.isNotEmpty(smsRecordDTO.getUserId()), "t.user_id", smsRecordDTO.getUserId());
    if (ObjectUtils.isNotEmpty(smsRecordDTO.getStatus())){
        if(smsRecordDTO.getStatus() == "-1"){
            wrapper.and(i -> i.ne("t.status", "0").ne("t.status", "3"));
        }else{
            wrapper.eq(ObjectUtils.isNotEmpty(smsRecordDTO.getStatus()), "t.status", smsRecordDTO.getStatus());
        }
    }
    wrapper.orderByDesc("t.push_time");
    Page page = new Page();
    // 设置当前页码
    page.setCurrent(smsRecordDTO.getPage());
    // 设置页大小
    page.setSize(smsRecordDTO.getLimit());
    IPage ipage = this.baseMapper.selectSmsRecordPageList(page, wrapper);
    return new PageVo(ipage);
}
 
Example 9
Source File: QueryGenerator.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
/**
  * 根据权限相关配置 组装mp需要的权限
 * @param searchObj
 * @param parameterMap
 * @return
 */
public static void installAuthMplus(QueryWrapper<?> queryWrapper,Class<?> clazz) {
	//权限查询
	Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
		}
	}
	String name;
	for (int i = 0; i < origDescriptors.length; i++) {
		name = origDescriptors[i].getName();
		if (judgedIsUselessField(name)) {
			continue;
		}
		if(ruleMap.containsKey(name)) {
			addRuleToQueryWrapper(ruleMap.get(name), name, origDescriptors[i].getPropertyType(), queryWrapper);
		}
	}
}
 
Example 10
Source File: MyBatisAccessor.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> List<T> queryIntersection(Class<T> clazz, Map<String, Object> condition, StoragePagination pagination) {
	MyBatisMetadata metadata = metadatas.get(clazz);
	BaseMapper mapper = template.getMapper(metadata.getMapperClass());
	QueryWrapper<?> query = new QueryWrapper<>();
	for (Entry<String, Object> term : condition.entrySet()) {
		query.and((wrapper) -> {
			return wrapper.eq(metadata.getColumnName(term.getKey()), term.getValue());
		});
	}
	if (pagination == null) {
		return mapper.selectList(query);
	} else {
		IPage<T> page = mapper.selectPage(new Page(pagination.getPage(), pagination.getSize()), query);
		return page.getRecords();
	}
}
 
Example 11
Source File: SmsRecordServiceImpl.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
@Override
public Integer findUnreadMessagesCount(Long userId) {
    QueryWrapper<SmsRecord> wrapper = new QueryWrapper<>();
    wrapper.eq("user_id", userId);
    wrapper.and(i -> i.ne("status", "0").ne("status", "3"));
    wrapper.orderByDesc("push_time");
    return this.count(wrapper);
}
 
Example 12
Source File: QueryWrapperUtil.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static <T> QueryWrapper<T> getWrapper(Object query) {
	QueryWrapper<T> entityWrapper = Wrappers.query();
	if (query == null) {
		return entityWrapper;
	}
	Field[] fields = ReflectUtil.getFields(query.getClass());
	try {
		for (Field field : fields) {
			boolean accessible = field.isAccessible();
			field.setAccessible(true);
			Query q = field.getAnnotation(Query.class);
			if (q != null) {
				String propName = q.propName();
				String blurry = q.blurry();
				String attributeName = StringUtil.isEmpty(propName) ? StringUtil.toRevertCamelCase(field.getName(), CharUtil.UNDERLINE) : propName;
				Object val = field.get(query);
				if (cn.hutool.core.util.ObjectUtil.isNull(val) || "".equals(val)) {
					continue;
				}
				// 模糊多字段
				if (cn.hutool.core.util.ObjectUtil.isNotEmpty(blurry)) {
					String[] blurrys = blurry.split(",");
					entityWrapper.and(i -> {
						for (String s : blurrys) {
							i.or().like(s, val.toString());
						}
					});
					continue;
				}
				parseWarpper(entityWrapper, q, attributeName, val);
			}
			field.setAccessible(accessible);
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
	return entityWrapper;
}
 
Example 13
Source File: MyBatisAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> void iterateIntersection(StorageIterator<T> iterator, Class<T> clazz, Map<String, Object> condition, StoragePagination pagination) {
	MyBatisMetadata metadata = metadatas.get(clazz);
	BaseMapper mapper = template.getMapper(metadata.getMapperClass());
	QueryWrapper<?> query = new QueryWrapper<>();
	for (Entry<String, Object> term : condition.entrySet()) {
		query.and((wrapper) -> {
			return wrapper.eq(metadata.getColumnName(term.getKey()), term.getValue());
		});
	}
	IPage<T> page = mapper.selectPage(new Page(pagination.getPage(), pagination.getSize()), query);
	for (T object : page.getRecords()) {
		iterator.iterate(object);
	}
}
 
Example 14
Source File: MyBatisAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> long countIntersection(Class<T> clazz, Map<String, Object> condition) {
	MyBatisMetadata metadata = metadatas.get(clazz);
	BaseMapper mapper = template.getMapper(metadata.getMapperClass());
	QueryWrapper<?> query = new QueryWrapper<>();
	for (Entry<String, Object> term : condition.entrySet()) {
		query.and((wrapper) -> {
			return wrapper.eq(metadata.getColumnName(term.getKey()), term.getValue());
		});
	}
	return mapper.selectCount(query);
}
 
Example 15
Source File: LoginRestApi.java    From mogu_blog_v2 with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "用户登录", notes = "用户登录")
@PostMapping("/login")
public String login(@Validated({GetOne.class}) @RequestBody UserVO userVO, BindingResult result) {
    ThrowableUtils.checkParamArgument(result);
    String userName = userVO.getUserName();
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.and(wrapper -> wrapper.eq(SQLConf.USER_NAME, userName).or().eq(SQLConf.EMAIL, userName));
    queryWrapper.last("limit 1");
    User user = userService.getOne(queryWrapper);
    if (user == null || EStatus.DISABLED == user.getStatus()) {
        return ResultUtil.result(SysConf.ERROR, "用户不存在");
    }

    if (EStatus.FREEZE == user.getStatus()) {
        return ResultUtil.result(SysConf.ERROR, "用户账号未激活");
    }

    if (StringUtils.isNotEmpty(user.getPassWord()) && user.getPassWord().equals(MD5Utils.string2MD5(userVO.getPassWord()))) {
        // 更新登录信息
        HttpServletRequest request = RequestHolder.getRequest();
        String ip = IpUtils.getIpAddr(request);
        Map<String, String> userMap = IpUtils.getOsAndBrowserInfo(request);
        user.setBrowser(userMap.get(SysConf.BROWSER));
        user.setOs(userMap.get(SysConf.OS));
        user.setLastLoginIp(ip);
        user.setLastLoginTime(new Date());
        user.updateById();
        // 获取用户头像
        if (!StringUtils.isEmpty(user.getAvatar())) {
            String avatarResult = pictureFeignClient.getPicture(user.getAvatar(), ",");
            List<String> picList = webUtil.getPicture(avatarResult);
            if (picList != null && picList.size() > 0) {
                user.setPhotoUrl(webUtil.getPicture(avatarResult).get(0));
            }
        }
        // 生成token
        String token = StringUtils.getUUID();

        // 过滤密码
        user.setPassWord("");
        //将从数据库查询的数据缓存到redis中
        redisUtil.setEx(SysConf.USER_TOEKN + SysConf.REDIS_SEGMENTATION + token, JsonUtils.objectToJson(user), userTokenSurvivalTime, TimeUnit.HOURS);

        return ResultUtil.result(SysConf.SUCCESS, token);
    } else {
        return ResultUtil.result(SysConf.ERROR, "账号或密码错误");
    }
}
 
Example 16
Source File: QueryGenerator.java    From teaching with Apache License 2.0 4 votes vote down vote up
/**
 * 组装Mybatis Plus 查询条件
 * <p>使用此方法 需要有如下几点注意:   
 * <br>1.使用QueryWrapper 而非LambdaQueryWrapper;
 * <br>2.实例化QueryWrapper时不可将实体传入参数   
 * <br>错误示例:如QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>(jeecgDemo);
 * <br>正确示例:QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>();
 * <br>3.也可以不使用这个方法直接调用 {@link #initQueryWrapper}直接获取实例
 */
public static void installMplus(QueryWrapper<?> queryWrapper,Object searchObj,Map<String, String[]> parameterMap) {
	
	/*
	 * 注意:权限查询由前端配置数据规则 当一个人有多个所属部门时候 可以在规则配置包含条件 orgCode 包含 #{sys_org_code}
	但是不支持在自定义SQL中写orgCode in #{sys_org_code} 
	当一个人只有一个部门 就直接配置等于条件: orgCode 等于 #{sys_org_code} 或者配置自定义SQL: orgCode = '#{sys_org_code}'
	*/
	
	//区间条件组装 模糊查询 高级查询组装 简单排序 权限查询
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(searchObj);
	Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
	
	//权限规则自定义SQL表达式
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
		}
	}
	
	String name, type;
	for (int i = 0; i < origDescriptors.length; i++) {
		//aliasName = origDescriptors[i].getName();  mybatis  不存在实体属性 不用处理别名的情况
		name = origDescriptors[i].getName();
		type = origDescriptors[i].getPropertyType().toString();
		try {
			if (judgedIsUselessField(name)|| !PropertyUtils.isReadable(searchObj, name)) {
				continue;
			}
			
			//数据权限查询
			if(ruleMap.containsKey(name)) {
				addRuleToQueryWrapper(ruleMap.get(name), name, origDescriptors[i].getPropertyType(), queryWrapper);
			}
			
			// 添加 判断是否有区间值
			String endValue = null,beginValue = null;
			if (parameterMap != null && parameterMap.containsKey(name + BEGIN)) {
				beginValue = parameterMap.get(name + BEGIN)[0].trim();
				addQueryByRule(queryWrapper, name, type, beginValue, QueryRuleEnum.GE);
				
			}
			if (parameterMap != null && parameterMap.containsKey(name + END)) {
				endValue = parameterMap.get(name + END)[0].trim();
				addQueryByRule(queryWrapper, name, type, endValue, QueryRuleEnum.LE);
			}
			
			//判断单值  参数带不同标识字符串 走不同的查询
			//TODO 这种前后带逗号的支持分割后模糊查询需要否 使多选字段的查询生效
			Object value = PropertyUtils.getSimpleProperty(searchObj, name);
			if (null != value && value.toString().startsWith(COMMA) && value.toString().endsWith(COMMA)) {
				String multiLikeval = value.toString().replace(",,", COMMA);
				String[] vals = multiLikeval.substring(1, multiLikeval.length()).split(COMMA);
				final String field = oConvertUtils.camelToUnderline(name);
				if(vals.length>1) {
					queryWrapper.and(j -> {
						j = j.like(field,vals[0]);
						for (int k=1;k<vals.length;k++) {
							j = j.or().like(field,vals[k]);
						}
						return j;
					});
				}else {
					queryWrapper.and(j -> j.like(field,vals[0]));
				}
			}else {
				//根据参数值带什么关键字符串判断走什么类型的查询
				QueryRuleEnum rule = convert2Rule(value);
				value = replaceValue(rule,value);
				// add -begin 添加判断为字符串时设为全模糊查询
				//if( (rule==null || QueryRuleEnum.EQ.equals(rule)) && "class java.lang.String".equals(type)) {
					// 可以设置左右模糊或全模糊,因人而异
					//rule = QueryRuleEnum.LIKE;
				//}
				// add -end 添加判断为字符串时设为全模糊查询
				addEasyQuery(queryWrapper, name, rule, value);
			}
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	// 排序逻辑 处理 
	doMultiFieldsOrder(queryWrapper, parameterMap);
			
	//高级查询
	doSuperQuery(queryWrapper, parameterMap);
	
}
 
Example 17
Source File: QueryGenerator.java    From jeecg-boot-with-activiti with MIT License 4 votes vote down vote up
/**
 * 组装Mybatis Plus 查询条件
 * <p>使用此方法 需要有如下几点注意:   
 * <br>1.使用QueryWrapper 而非LambdaQueryWrapper;
 * <br>2.实例化QueryWrapper时不可将实体传入参数   
 * <br>错误示例:如QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>(jeecgDemo);
 * <br>正确示例:QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>();
 * <br>3.也可以不使用这个方法直接调用 {@link #initQueryWrapper}直接获取实例
 */
public static void installMplus(QueryWrapper<?> queryWrapper,Object searchObj,Map<String, String[]> parameterMap) {
	
	/*
	 * 注意:权限查询由前端配置数据规则 当一个人有多个所属部门时候 可以在规则配置包含条件 orgCode 包含 #{sys_org_code}
	但是不支持在自定义SQL中写orgCode in #{sys_org_code} 
	当一个人只有一个部门 就直接配置等于条件: orgCode 等于 #{sys_org_code} 或者配置自定义SQL: orgCode = '#{sys_org_code}'
	*/
	
	//区间条件组装 模糊查询 高级查询组装 简单排序 权限查询
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(searchObj);
	Map<String,SysPermissionDataRule> ruleMap = getRuleMap();
	
	//权限规则自定义SQL表达式
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
		}
	}
	
	String name, type;
	for (int i = 0; i < origDescriptors.length; i++) {
		//aliasName = origDescriptors[i].getName();  mybatis  不存在实体属性 不用处理别名的情况
		name = origDescriptors[i].getName();
		type = origDescriptors[i].getPropertyType().toString();
		try {
			if (judgedIsUselessField(name)|| !PropertyUtils.isReadable(searchObj, name)) {
				continue;
			}
			
			//数据权限查询
			if(ruleMap.containsKey(name)) {
				addRuleToQueryWrapper(ruleMap.get(name), name, origDescriptors[i].getPropertyType(), queryWrapper);
			}
			
			// 添加 判断是否有区间值
			String endValue = null,beginValue = null;
			if (parameterMap != null && parameterMap.containsKey(name + BEGIN)) {
				beginValue = parameterMap.get(name + BEGIN)[0].trim();
				addQueryByRule(queryWrapper, name, type, beginValue, QueryRuleEnum.GE);
				
			}
			if (parameterMap != null && parameterMap.containsKey(name + END)) {
				endValue = parameterMap.get(name + END)[0].trim();
				addQueryByRule(queryWrapper, name, type, endValue, QueryRuleEnum.LE);
			}
			
			//判断单值  参数带不同标识字符串 走不同的查询
			//TODO 这种前后带逗号的支持分割后模糊查询需要否 使多选字段的查询生效
			Object value = PropertyUtils.getSimpleProperty(searchObj, name);
			if (null != value && value.toString().startsWith(COMMA) && value.toString().endsWith(COMMA)) {
				String multiLikeval = value.toString().replace(",,", COMMA);
				String[] vals = multiLikeval.substring(1, multiLikeval.length()).split(COMMA);
				final String field = oConvertUtils.camelToUnderline(name);
				if(vals.length>1) {
					queryWrapper.and(j -> {
						j = j.like(field,vals[0]);
						for (int k=1;k<vals.length;k++) {
							j = j.or().like(field,vals[k]);
						}
						return j;
					});
				}else {
					queryWrapper.and(j -> j.like(field,vals[0]));
				}
			}else {
				//根据参数值带什么关键字符串判断走什么类型的查询
				QueryRuleEnum rule = convert2Rule(value);
				value = replaceValue(rule,value);
				// add -begin 添加判断为字符串时设为全模糊查询
				//if( (rule==null || QueryRuleEnum.EQ.equals(rule)) && "class java.lang.String".equals(type)) {
					// 可以设置左右模糊或全模糊,因人而异
					//rule = QueryRuleEnum.LIKE;
				//}
				// add -end 添加判断为字符串时设为全模糊查询
				addEasyQuery(queryWrapper, name, rule, value);
			}
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	// 排序逻辑 处理 
	doMultiFieldsOrder(queryWrapper, parameterMap);
			
	//高级查询
	doSuperQuery(queryWrapper, parameterMap);
	
}
 
Example 18
Source File: BlogServiceImpl.java    From mogu_blog_v2 with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> getBlogByKeyword(String keywords, Long currentPage, Long pageSize) {
    final String keyword = keywords.trim();
    QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
    queryWrapper.and(wrapper -> wrapper.like(SQLConf.TITLE, keyword).or().like(SQLConf.SUMMARY, keyword));
    queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
    queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH);
    queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT));
    queryWrapper.orderByDesc(SQLConf.CLICK_COUNT);
    Page<Blog> page = new Page<>();
    page.setCurrent(currentPage);
    page.setSize(pageSize);

    IPage<Blog> iPage = blogService.page(page, queryWrapper);

    List<Blog> blogList = iPage.getRecords();

    List<String> blogSortUidList = new ArrayList<>();
    Map<String, String> pictureMap = new HashMap<>();
    final StringBuffer fileUids = new StringBuffer();

    blogList.forEach(item -> {

        // 获取图片uid
        blogSortUidList.add(item.getBlogSortUid());
        if (StringUtils.isNotEmpty(item.getFileUid())) {
            fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION);
        }

        // 给标题和简介设置高亮
        item.setTitle(getHitCode(item.getTitle(), keyword));
        item.setSummary(getHitCode(item.getTitle(), keyword));

    });

    // 调用图片接口,获取图片
    String pictureList = null;
    if (fileUids != null) {
        pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION);
    }
    List<Map<String, Object>> picList = webUtil.getPictureMap(pictureList);

    picList.forEach(item -> {
        pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString());
    });

    Collection<BlogSort> blogSortList = new ArrayList<>();
    if (blogSortUidList.size() > 0) {
        blogSortList = blogSortService.listByIds(blogSortUidList);
    }

    Map<String, String> blogSortMap = new HashMap<>();
    blogSortList.forEach(item -> {
        blogSortMap.put(item.getUid(), item.getSortName());
    });

    // 设置分类名 和 图片
    blogList.forEach(item -> {
        if (blogSortMap.get(item.getBlogSortUid()) != null) {
            item.setBlogSortName(blogSortMap.get(item.getBlogSortUid()));
        }

        //获取图片
        if (StringUtils.isNotEmpty(item.getFileUid())) {
            List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), SysConf.FILE_SEGMENTATION);
            List<String> pictureListTemp = new ArrayList<>();

            pictureUidsTemp.forEach(picture -> {
                pictureListTemp.add(pictureMap.get(picture));
            });
            // 只设置一张标题图
            if (pictureListTemp.size() > 0) {
                item.setPhotoUrl(pictureListTemp.get(0));
            } else {
                item.setPhotoUrl("");
            }
        }
    });


    Map<String, Object> map = new HashMap<>();

    // 返回总记录数
    map.put(SysConf.TOTAL, iPage.getTotal());

    // 返回总页数
    map.put(SysConf.TOTAL_PAGE, iPage.getPages());

    // 返回当前页大小
    map.put(SysConf.PAGE_SIZE, pageSize);

    // 返回当前页
    map.put(SysConf.CURRENT_PAGE, iPage.getCurrent());

    // 返回数据
    map.put(SysConf.BLOG_LIST, blogList);

    return map;
}
 
Example 19
Source File: LoginRestApi.java    From mogu_blog_v2 with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "用户注册", notes = "用户注册")
@PostMapping("/register")
public String register(@Validated({Insert.class}) @RequestBody UserVO userVO, BindingResult result) {
    ThrowableUtils.checkParamArgument(result);
    if(userVO.getUserName().length() < 5 || userVO.getUserName().length() >= 20 || userVO.getPassWord().length() < 5 || userVO.getPassWord().length() >= 20) {
        return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
    }
    HttpServletRequest request = RequestHolder.getRequest();
    String ip = IpUtils.getIpAddr(request);
    Map<String, String> map = IpUtils.getOsAndBrowserInfo(request);
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.and(wrapper -> wrapper.eq(SQLConf.USER_NAME, userVO.getUserName()).or().eq(SQLConf.EMAIL, userVO.getEmail()));
    queryWrapper.eq(SysConf.STATUS, EStatus.ENABLE);
    User user = userService.getOne(queryWrapper);
    if (user != null) {
        return ResultUtil.result(SysConf.ERROR, "用户已存在");
    }
    user = new User();
    user.setUserName(userVO.getUserName());
    user.setNickName(userVO.getNickName());
    user.setPassWord(MD5Utils.string2MD5(userVO.getPassWord()));
    user.setEmail(userVO.getEmail());
    // 设置账号来源,蘑菇博客
    user.setSource("MOGU");
    user.setLastLoginIp(ip);
    user.setBrowser(map.get(SysConf.BROWSER));
    user.setOs(map.get(SysConf.OS));
    user.setStatus(EStatus.FREEZE);
    user.insert();

    // 生成随机激活的token
    String token = StringUtils.getUUID();

    // 过滤密码
    user.setPassWord("");

    //将从数据库查询的数据缓存到redis中,用于用户邮箱激活,1小时后过期
    redisUtil.setEx(RedisConf.ACTIVATE_USER + RedisConf.SEGMENTATION + token, JsonUtils.objectToJson(user), 1, TimeUnit.HOURS);

    // 发送邮件,进行账号激活
    rabbitMqUtil.sendActivateEmail(user, token);

    return ResultUtil.result(SysConf.SUCCESS, "注册成功,请登录邮箱进行账号激活");
}