Springboot MongoDB 使用笔记-对象拷贝

1 分页、排序

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Collection;
import java.util.List;


@ApiModel(description = "分页实体")
@Data
public class Page<T> {

    @ApiModelProperty(value = "总页数")
    private Long totalPage;

    @ApiModelProperty(value = "总记录数")
    private Long totalCount;

    @ApiModelProperty(value = "数据")
    private Collection<T> data;

    @ApiModelProperty(value = "当前页数")
    private Long currentPage;

    @ApiModelProperty(value = "每页显示条数")
    private Long pageSize;

    public Page() {
    }

    /**
     * @param data        数据
     * @param totalCount  显示数据数量
     * @param currentPage 当前页
     * @param pageSize    每页显示条数
     */
    public Page(Collection<T> data, Long totalCount, Integer currentPage, Integer pageSize) {
        this.totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        this.totalCount = totalCount;
        this.data = data;
        this.currentPage = Long.valueOf(currentPage);
        this.pageSize = Long.valueOf(pageSize);
    }
}


        Query query = new Query();
        Criteria criteria = new Criteria();
        if ("" != prizeName) {
            criteria.and("prizeName").is(prizeName);
        }
   		query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC, "createTime")); //createTime 升序
        //默认显示页10条
        query.skip((currentPage - 1) * pageSize).limit(pageSize);
        List<ActivityPrize> list = mongoTemplate.find(query, ActivityPrize.class);
        long count = mongoTemplate.count(query, ActivityPrize.class);
        /**
         * 封装分页返回数据
         */
        Page<ActivityPrize> page = new Page<>(list, count, currentPage, pageSize);

当没有任何条件时,查出所以文档数据

2 批处理

 @Test
    public void testAccount() {
        BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Account.class);
        List<Account> list = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            Account account = new Account();
            account.setUserName("admin" + i);
            account.setPassWord("password");
            list.add(account);
        }
        ops.insert(list);
        ops.execute();

    }

Springboot MongoDB 使用笔记-对象拷贝_第1张图片

3 文档嵌套对象

public class Account{
	...
 	private Set<Role> roles = new HashSet<>();
}
@Test
    public void test9() {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("_id").is("364FF769E55A419D8A0F3712C84291AF").and("roles.name").is("admin");
        query.addCriteria(criteria);
        log.debug("result:{}", mongoTemplate.find(query, Account.class));

        //Update update =  Update.update("roles.$.name","admin1");//修改匹配的第一个
        Update update = Update.update("roles.$[].name", "admin1");//修改匹配的所有

        UpdateResult result = mongoTemplate.updateMulti(query, update, Account.class);
        log.debug("UpdateResult:{}", result1);
    }

4 andOperator /orOperator

andOperator orOperator在一个query语句的Criteria中只允许使用一次,多个条件使用
Criteria andOperator(Criteria... criteria)Criteria orOperator(Criteria... criteria)方法加入
Springboot MongoDB 使用笔记-对象拷贝_第2张图片

例如:

Criteria criteria = new Criteria();

Criteria quantityCriteria1 = new Criteria();
 if (inventoryMin != null) {      
            quantityCriteria1.and("inventoryQuantity").gte(inventoryMin);
        }
Criteria quantityCriteria2 = new Criteria();
if (inventoryMax != null) {       
            quantityCriteria2.and("inventoryQuantity").lte(inventoryMax);
        }
criteria.andOperator(quantityCriteria1, quantityCriteria2);
query.addCriteria(criteria);
 criteria.orOperator( Criteria.where("prizeValidStartDate").lt(new Date()),
                        Criteria.where("prizeValidEndDate").gt(new Date())
                );

或查询可使用in查询

List<String> roleNameList

Criteria criteria = new Criteria();
criteria.and("roleName").in(roleNameList);

数据可以是集合类型

 public Criteria in(Collection<?> c) {
        this.criteria.put("$in", c);
        return this;
    }

5 对象拷贝更新实体

MongoTemplatesave方法既可以保存实体也可以更新,如果使用update更新字段多的实体将会非常繁琐,所以使用对象拷贝更新实体。

//先从数据库查询出数据
Query query = new Query(Criteria.where("_id").is(accountId));
Account queryAccount = mongoTemplate.findOne(query, Account.class);

//前端的修改数据
Account account

//对象拷贝,非空字段拷贝
BeanUtils.copyProperties(account, queryAccount, getNullPropertyNames(account));

//保存拷贝字段后的实体
mongoTemplate.save(queryAccount);

去除非空字段,即页面没有输入或者修改的数据,将会不会覆盖

getNullPropertyNames(account)
 public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

你可能感兴趣的:(MongoDB)