1、查询部分属性
EntityRepository基础仓库类
package com.fun.website.common;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface EntityRepository<T> extends MongoRepository<T, String> {
}
AccountRepository账户仓库类
package com.fun.website.module.account.manager;
import org.springframework.data.mongodb.repository.Query;
import com.fun.website.common.EntityRepository;
public interface AccountRepository extends EntityRepository<Account> {
@Query(value="{ 'username' : ?0 }", fields="{ 'username' : 1, '_id' : 0}")
Account findByUsername(String username);
@Query(value="{ 'type': {'$in' : ?0} }",fields="{ 'type' : 1}")
public List<Account> findTest(String[] name);
@Query(value="{?0:?1}")
public List<Account> findTest2(Object field,Object Value);
//正则测试
@Query(value="{ 'type' :{'$regex' :?0, '$options': 'i'} }")
public List<Account> findTest3(String name);
//日期查询
@Query(value="{ 'executeDate' :{'$gt' : ?0 } }")
public List<Account> findTest4(Date date);
//内部查询 findBy{字段}{条件}
public List<Account> findByTypeLike(String name);
public List<Account> findByTypeLike(String name, Sort sort);
public List<Account> findByTypeLike(String name, Pageable pageable);
}
其中“@Query(value="{ 'username' : ?0 }", fields="{ 'username' : 1, '_id' : 0}")”,value是查询条件,fields指定查询部分属性,默认查询全部属性。
2、bean的配置属性
它有以下几种注释:
@Id - 文档的唯一标识,在mongodb中为ObjectId,它是唯一的,通过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成。
@Document - 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
@DBRef - 声明类似于关系数据库的关联关系。ps:暂不支持级联的保存功能,当你在本实例中修改了DERef对象里面的值时,单独保存本实例并不能保存DERef引用的对象,它要另外保存,如下面例子的Person和Account。
@Indexed - 声明该字段需要索引,建索引可以大大的提高查询效率。
@CompoundIndex - 复合索引的声明,建复合索引可以有效地提高多字段的查询效率。
@GeoSpatialIndexed - 声明该字段为地理信息的索引。
@Transient - 映射忽略的字段,该字段不会保存到mongodb。
@PersistenceConstructor - 声明构造函数,作用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据。
以下引用一个官方文档的例子:
Person类:
@Document(collection="person")
@CompoundIndexes({
@CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}")
})
public class Person<T extends Address> {
@Id
private String id;
@Indexed(unique = true)
private Integer ssn;
private String firstName;
@Indexed
private String lastName;
private Integer age;
@Transient
private Integer accountTotal;
@DBRef
private List<Account> accounts;
private T address;
public Person(Integer ssn) {
this.ssn = ssn;
}
@PersistenceConstructor
public Person(Integer ssn, String firstName, String lastName, Integer age, T address) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}