JPA自定义SimpleRepository

定义

1.自定义模板接口声明

@NoRepositoryBean
public interface CustomeRepository<T, ID extends Serializable> extends MongoRepository<T, ID> 

你可以在这里定义你的方法

2.实现自定义模板接口并继承SimpleRepository

public class SimpleBaseRepository<T, ID extends Serializable> extends SimpleRepository<T, ID> implements CustomeRepository<T, ID> {

这里需要实现你定义的方法,通常,还需要构造到父类,以完全继承父类

3.声明的数据repo接口继承模板接口

@Configuration
@EnableRepositories(repositoryBaseClass = SimpleBaseRepository.class, basePackages = {"x.x.dao"})
public class RepositoryConfig {
}

实现示例

/**
 * 自定义SimpleRepository for Mongo
 * @author created by vinson on 2019/8/28
 */
public class SimpleBaseMongoRepository<T, ID extends Serializable> extends SimpleMongoRepository<T, ID> implements FaceMongoRepository<T, ID> {

    private final MongoOperations mongoOperations;

    private final MongoEntityInformation<T, ID> entityInformation;

    public SimpleBaseMongoRepository(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
        super(metadata, mongoOperations);
        this.mongoOperations = mongoOperations;
        this.entityInformation = metadata;
    }

    private Class<T> getEntityClass() {
        return entityInformation.getJavaType();
    }

    @Override
    public MongoCursor<T> find(List<? extends Bson> pipeline) {
        CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        return mongoOperations.getCollection(entityInformation.getCollectionName()).withCodecRegistry(pojoCodecRegistry).aggregate(pipeline, entityInformation.getJavaType()).iterator();
    }

    @Override
    public List<T> find(Criteria criteria) {
        return mongoOperations.find(new Query(criteria), getEntityClass());
    }

    @Override
    public Page<T> findPageByQuery(Query query, Pageable pageable) {
        long total = mongoOperations.count(query, getEntityClass());
        List<T> list = mongoOperations.find(query.with(pageable), getEntityClass());
        return new PageImpl<T>(list, pageable, total);
    }

    @Override
    public Page<T> findPageByCriteria(Criteria criteria, Pageable pageable) {
        return findPageByQuery(new Query(criteria), pageable);
    }

    @Override
    public T findOneByQuery(Query query) {
        return mongoOperations.findOne(query, getEntityClass());
    }

    @Override
    public T findOneByCriteria(Criteria criteria) {
        return findOneByQuery(new Query(criteria));
    }

    @Override
    public Long countByCriteria(Criteria criteria) {
        return mongoOperations.count(new Query(criteria), getEntityClass());
    }
}

自此,你可以通过定义JPA接口并继承自定义的接口,来使用实现的方法

@Repository
public interface ProjectOperatorRepo extends CustomeRepository<Object, ObjectId> {
}

其他

我在mongo-driver中定义cursor查询器时遇到了CodecRegistry的问题,在上面的返回MongoCursor的find方法中解决了,解决方案在官网有说明