Spring 为java web 开发领域提供了大量的优秀的框架,第三方包,大大解放了生产力,本文主要介绍Spring Repository在连接数据库这边做的一些封装,并以Mongo Repository为例,详细阐述下Repository实现机制,本文基于spring-data-mongo1.10.4
在使用Repository的时候,相信很多人都有下面的疑问,本文就是致力于解决这些疑惑
一个根据userId找帖子的Repository方法
@Repository
public interface PostRepository extends MongoRepository<Post,String> {
Post findTopByUserId(Long userId);
}

private final PartTree.Subject subject;private final PartTree.Predicate predicate; result.addAdvice(new RepositoryFactorySupport.QueryExecutorMethodInterceptor(information, customImplementation, target));private Object doInvoke(MethodInvocation invocation) throws Throwable {Method method = invocation.getMethod();Object[] arguments = invocation.getArguments();Method actualMethod;if(this.isCustomMethodInvocation(invocation)) { actualMethod = this.repositoryInformation.getTargetClassMethod(method);return this.executeMethodOn(this.customImplementation, actualMethod, arguments);} else if(this.hasQueryFor(method)) {// 执行RepositoryQuery.execute方法return ((RepositoryQuery)this.queries.get(method)).execute(arguments);} else { actualMethod = this.repositoryInformation.getTargetClassMethod(method);return this.executeMethodOn(this.target, actualMethod, arguments);}}
public Object execute(Object[] parameters) {MongoParameterAccessor accessor = new MongoParametersParameterAccessor(this.method, parameters);// 构建query条件Query query = this.createQuery(new ConvertingParameterAccessor(this.operations.getConverter(), accessor));this.applyQueryMetaAttributesWhenPresent(query);ResultProcessor processor = this.method.getResultProcessor().withDynamicProjection(accessor);String collection = this.method.getEntityInformation().getCollectionName();MongoQueryExecution execution = this.getExecution(query, accessor, new ResultProcessingConverter(processor, this.operations, this.instantiators));return execution.execute(query, processor.getReturnedType().getDomainType(), collection);}