一、基础类配置
@NoRepositoryBean
public interface IMongoRepository<T, ID> extends MongoRepository<T, ID> {String getTableName();void deleteAll(Collection<ID> ids);MongoOperations getMongoOperations();MongoEntityInformation<T, ID> getEntityInformation();Class<T> getEntityClass();Class<ID> getIdClass();
}
public class AbstractMongoRepository<T, ID> extends SimpleMongoRepository<T, ID> implements IMongoRepository<T, ID> {private final MongoOperations mongoOperations;private final MongoEntityInformation<T, ID> entityInformation;public AbstractMongoRepository(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {super(metadata, mongoOperations);this.mongoOperations = mongoOperations;this.entityInformation = metadata;}@Overridepublic String getTableName(){return entityInformation.getCollectionName();}@Overridepublic void deleteAll(Collection<ID> ids) {ids.forEach(this::deleteById);}@Overridepublic MongoOperations getMongoOperations() {return mongoOperations;}@Overridepublic MongoEntityInformation<T, ID> getEntityInformation() {return entityInformation;}@Overridepublic Class<T> getEntityClass() {return entityInformation.getJavaType();}@Overridepublic Class<ID> getIdClass() {return entityInformation.getIdType();}
}
@SpringBootApplication
@EnableMongoRepositories(repositoryBaseClass = AbstractMongoRepository.class)
public class MongoApplication {public static void main(String[] args) {SpringApplication.run(MongoApplication.class, args);}
}
而、查询
(1)普通查询
public interface UserRepository extends IMongoRepository<User, ObjectId> {//jpa根据名字自动适配查询List<User> findByName(String name);List<User> findByNameAndAge(String name, int age);//手动指定查询default List<User> listByNameAndAge(String name, int age){Query q = new Query(Criteria.where(User.Fields.name).is(name).and(User.Fields.age).is(age));return this.getMongoOperations().find(q, this.getEntityClass());}default List<User> find(ObjectId id){Query q = new Query(Criteria.where("_id").is(id));return this.getMongoOperations().find(q, this.getEntityClass());}default Optional<User> find2(ObjectId id){return this.findById(id);}default List<User> listByAge(int ageMin,int ageMax) {Query q = new Query(Criteria.where(User.Fields.name).exists(true).andOperator(Criteria.where(User.Fields.age).gte(ageMin),Criteria.where(User.Fields.age).lt(ageMax)));return this.getMongoOperations().find(q, User.class, this.getTableName());}}
(2)排序
public interface UserRepository extends IMongoRepository<User, ObjectId> {default List<User> listSort(int age){Query q = new Query(Criteria.where(User.Fields.age).is(age));q.with(Sort.by(Sort.Order.desc(User.Fields.name), Sort.Order.desc(User.Fields.age)));return this.getMongoOperations().find(q, this.getEntityClass());}}
(3)分页
public interface UserRepository extends IMongoRepository<User, ObjectId> {default List<User> listLimit(int age){Query q = new Query(Criteria.where(User.Fields.age).is(age));q.skip(50).limit(10);return this.getMongoOperations().find(q, this.getEntityClass());}}
二、更新
public interface UserRepository extends IMongoRepository<User, ObjectId> {default void update(User user){this.save(user);}default long updateAge(ObjectId id, int age){Query q = new Query(Criteria.where("_id").is(id));Update update = new Update();update.set(User.Fields.age, age);return this.getMongoOperations().updateFirst(q, update, getTableName()).getModifiedCount();}default long updateAge(String name, int age){Query q = new Query(Criteria.where(User.Fields.name).is(name));Update update = new Update();update.set(User.Fields.age, age);return this.getMongoOperations().updateMulti(q, update, getTableName()).getModifiedCount();}
}
三、删除
public interface UserRepository extends IMongoRepository<User, ObjectId> {default void delete(ObjectId id){this.deleteById(id);}default void delete1(User user){this.delete(user);}default DeleteResult delete2(ObjectId id){Query q = new Query(Criteria.where("_id").is(id));return this.getMongoOperations().remove(q, getTableName());}
}
四、索引
public interface UserRepository extends IMongoRepository<User, ObjectId> {default void createIndex() {MongoCollection<Document> collection = getMongoOperations().getCollection(getTableName());BasicDBObject indexOptions = new BasicDBObject();indexOptions.put(User.Fields.name, -1);String alarmSummaryId = collection.createIndex(indexOptions);indexOptions = new BasicDBObject();indexOptions.put(User.Fields.age, 1);String createAt = collection.createIndex(indexOptions);}
}
五、聚合
public interface UserRepository extends IMongoRepository<User, ObjectId> {default Map<ObjectId,String> listAgeFirstCity(int skip, int limit){Criteria criteria = Criteria.where(User.Fields.city).exists(true);Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),Aggregation.group(User.Fields.age).first( "$city").as( "city"),Aggregation.skip(skip), Aggregation.limit(limit));List<Map> list = this.getMongoOperations().aggregate(aggregation, getTableName(), Map.class).getMappedResults();Map<ObjectId, String> data = new HashMap<>();for(Map<String,Object> map : list){data.put((ObjectId) map.get("_id"), (String)map.get("city"));}return data;}
}
六、连接
public interface UserRepository extends IMongoRepository<User, ObjectId> {default List<UserVo> list() {LookupOperation lookupOperation= LookupOperation.newLookup().from(AdminRepository.instance().getTableName()). //关联从表名localField(User.Fields.name). //主表关联字段foreignField(Admin.Fields.name).//从表关联的字段as("adminInfo"); //查询结果名Criteria left = Criteria.where(User.Fields.city).exists(true).andOperator(Criteria.where(User.Fields.age).gte(18),Criteria.where(User.Fields.age).lt(65));Criteria right = Criteria.where("adminInfo.0").exists(true).and("adminInfo.0.admin").is(1);Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(left), lookupOperation, Aggregation.match(right), Aggregation.unwind("adminInfo", true));List<UserVo> results = this.getMongoOperations().aggregate(aggregation, this.getTableName(), UserVo.class).getMappedResults();return results;}@Setter@Getterpublic static class UserVo extends User{private Admin adminInfo;}}