首页 > 解决方案 > 如何从参数输入中进行自定义查询

问题描述

您好我目前正在尝试进行自定义查询,该查询可以通过我的存储库层中的参数输入。

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;



@Repository
 public interface LinuxServerTaniumReportRepository extends MongoRepository<LinuxServerTaniumReport, String> {

@Query(:query)
public List<LinuxServerTaniumReport> performQuery(String query);
}

我应该怎么做?

标签: javamongodb

解决方案


You can not do this via Annotation, but you can do this by providing a custom repository. It is something around this lines:

public interface MyCustomExecuteMethod<T> extends Repository {

    public List<T> performQuery(String query);

} 

public class MyCustomExecuteMethodProvider<T> implements MyCustomExecuteMethod {
   @Autowire
   EntityManager em;

   public List<T> performQuery(String query) {
      // put your logic here where you create the query via the entity manager 
   }

}


Repository
 public interface LinuxServerTaniumReportRepository extends MongoRepository<LinuxServerTaniumReport, String> ,MyCustomExecuteMethod<LinuxServerTaniumReport>{

}

Now the only thing you need to get this method is to extend your repositories with the interface MyCustomExecuteMethod. This technic is called spring data composable repositories it is covered in spring data documentation under chapter Custome Implementation of spring data repositories https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations


推荐阅读