【问题标题】:Jpql and hibernate age differencejpql和hibernate的年龄差
【发布时间】:2020-02-18 13:41:43
【问题描述】:

我想编写一个方法,以 5 年的时间间隔搜索给定年龄的人。也就是说,如果将年龄设置为 30 岁,那么该方法应该将所有人从 25 岁带到 35 岁。

  @Entity
@NamedQueries({
        @NamedQuery(name = "Person.findByNameUndSurname", query = "SELECT c FROM Person c WHERE c.name = ?1 and c.surname = ?1"),
        @NamedQuery(name = "Person.findByAge", query = "SELECT c FROM Person c WHERE c.age = ?1")
})
    Person{
    name,age und get,set
    }

public class PersonMenager extends AbstractRepository {

---
    public List findPersonByAge(int age){
            return entityManager.createQuery("SELECT c from Person c WHERE c.age = ?1 and c.age between age-5 and  age+5").getResultList();
        }
}

我不明白如何使用年龄输入

【问题讨论】:

  • 嗨@Evg。如果答案已经解决了您的问题,请考虑通过单击复选标记接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做

标签: java hibernate jpa jpql


【解决方案1】:

查询将是:

SELECT c from Person c WHERE c.age between :age -5 and  :age + 5 

那你需要拨打query.setParameter("age", age)

如果可以使用更灵活的查询:

SELECT c from Person c WHERE c.age between :startAge and  :endAge

并设置de参数:

query.setParameter("startAge", age - 5);
query.setParameter("endAge", age + 5);

【讨论】:

    【解决方案2】:

    传递 2 个参数 - 下限和上限 - 否则您只能查询 +/- 5 年。如果你想要 +/- 3 怎么办?

    public class PersonMenager extends AbstractRepository {
    
        public List findPersonByAge(int lowerBound, int upperBound){
                return entityManager.createQuery("SELECT c from Person c 
                    WHERE c.age between ?1 and ?2).getResultList();
            }
    }
    

    存储年龄可能也不是一个好主意,因为它不是一个固定值(不像出生日期)。

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 2016-10-23
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2011-05-15
      • 1970-01-01
      相关资源
      最近更新 更多