Criteria类源码解读

Criteria类源码解读

1、Criteria类中的私有成员

	private static final Object NOT_SET = new Object();
	private @Nullable String key;
	//规则链
	private List<Criteria> criteriaChain;
	//条件查询的字符拼接Map
	private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
	private @Nullable Object isValue = NOT_SET;

2、Criteria类中的构造方法

public Criteria() {
		this.criteriaChain = new ArrayList<Criteria>();
	}

public Criteria(String key) {
		this.criteriaChain = new ArrayList<Criteria>();
		this.criteriaChain.add(this);
		this.key = key;
	}

protected Criteria(List<Criteria> criteriaChain, String key) {
		this.criteriaChain = criteriaChain;
		this.criteriaChain.add(this);
		this.key = key;
	}

3、常用方法

	//提供一个静态方法,设置关键字key,用来查询数据库
	public static Criteria where(String key) {
		return new Criteria(key);
	}

	//此方法会有设置一个键,并返回一个Criteria对象,进行链式调用实现逻辑与
	public Criteria and(String key) {
		return new Criteria(this.criteriaChain, key);
	}
	
	//通过一个条件查询对象链来构建一个Criteria对象
	protected Criteria(List<Criteria> criteriaChain, String key) {
		this.criteriaChain = criteriaChain;
		this.criteriaChain.add(this);
		this.key = key;
	}
	//通过一个匹配对象来构建Criteria对象
	public static Criteria byExample(Object example) {
		return byExample(Example.of(example));
	}
	
	//设置查询的条件,相当于等于的意思
	public Criteria is(@Nullable Object o) {
		if (!isValue.equals(NOT_SET)) {
			throw new InvalidMongoDbApiUsageException(
					"Multiple 'is' values declared. You need to use 'and' with multiple criteria");
		}
		if (lastOperatorWasNot()) {
			throw new InvalidMongoDbApiUsageException("Invalid query: 'not' can't be used with 'is' - use 'ne' instead.");
		}
		this.isValue = o;
		return this;
	}
	//相当于不等于 
	public Criteria ne(@Nullable Object o) {
		criteria.put("$ne", o);
		return this;
	}
	//相当于小于
	public Criteria lt(Object o) {
		criteria.put("$lt", o);
		return this;
	}
	//相当于大于
	public Criteria gt(Object o) {
		criteria.put("$gt", o);
		return this;
	}
	//条件查询的范围,相当于sql的in操作
	public Criteria in(Object... o) {
		if (o.length > 1 && o[1] instanceof Collection) {
			throw new InvalidMongoDbApiUsageException(
					"You can only pass in one argument of type " + o[1].getClass().getName());
		}
		criteria.put("$in", Arrays.asList(o));
		return this;
	}

4、主要执行流程

先看一段代码

Query query = new Query();
Criteria criteria = new Criteria();
criteria.and("status").is(0);
query.addCriteria(criteria);
List<Info> info= mongo.find(query, Info.class, collection_name);

意思是在名为collection_name的数据库中查找键为status为0的所有数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值