【问题标题】:How to use between and where condition together in Spring Data Mongo DB?如何在 Spring Data Mongodb 中同时使用 between 和 where 条件?
【发布时间】:2019-11-21 17:22:06
【问题描述】:

我有一个名为 Employee 的文档。我想查询2019年到2020年之间所有指定为“开发者”且加入日期为的员工。

class Employee{
    private String name;
    private String designation;
    private Date joiningDate;
}

**// i want where condition on designation to be included in the following** 
@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {
    @Query("{'joiningDate' : {$gte : ?0, $lte : ?1}}")
    public List<Employee> findByJoiningDateBetween(LocalDateTime startTime, LocalDateTime endTime);
}

【问题讨论】:

  • 您在使用 JPA 吗?为什么要扩展MongoRepository
  • @KenChan 是的。我需要我已经在条件之间。现在我想在另一列上添加 where 条件
  • 那为什么要扩展 MongoRepository 呢? JPA与RDBMS一起使用,与MongoDB完全不同......
  • @KenChan 对不起。这是 Mongo DB 而不是 JPA。我会更新问题。

标签: spring mongodb mongodb-query spring-data-mongodb


【解决方案1】:

真的,这不是 JPA,这是 Spring Data MongoDB。

这不是文档,文档必须注释为@Document 并具有@Id(String 或更好的 ObjectId)。

如果你想使用复杂的查询,也许更好的方法是使用自己的存储库方法实现:

public interface EmployeeRepository extends MongoRepository<Employee, String>, EmployeeRepositoryBase {
}

public interface EmployeeRepositoryBase {
    List<Employee> findByJoiningDateBetween(Date startDate, Date endDate);
}

@Repository
public class EmployeeRepositoryImpl implements EmployeeRepositoryBase {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Employee> findJoiningDateBetween(final Date startDate, final Date endDate) {
        final var query = Query.query(Criteria.where("...").is(...).and("...").gte(...).lte(...);
        return mongoTemplate(query, Employee.class);
    }
}

【讨论】:

  • 它的 Mongo DB 不是 JPA。
【解决方案2】:

在你的仓库中使用这种方式

List<Employee> findByJoiningDateBetween(Date startDate, Date endDate);

refer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多