【问题标题】:How to fetch list of objects with same phone number如何获取具有相同电话号码的对象列表
【发布时间】:2021-05-31 10:14:06
【问题描述】:

我有一个driving_info 的实体,其中包含很多字段,但其中一个是电话号码(从中订购)。 我要做的是获取从该号码订购的所有驱动器。但是当我尝试传递 phoneNumber 的 int 时,我得到了

query did not return a unique result: 5; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 5
org.springframework.dao.IncorrectResultSizeDataAccessException: query did not return a unique result: 5; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 5

我实际上想要结果列表,以便我可以获得从该电话号码订购的所有驱动器列表的响应。

我的控制器方法是

@GetMapping("/users/{phone}")
public List<User> getUserByPhone(@PathVariable int phone) {
   List<User> users= userService.findByPhone(phone);
   if(users == null) {
        throw new RuntimeException("User not found with "+phone+" phone number");
    }
    return users;
}

我的 DAO 是

@Override
@Transactional
public List<User> findByPhone(int phone) {
    Session currentSession = entityManager.unwrap(Session.class);
    Query<User> theQuery = currentSession.createQuery("from User where phone=:phone",User.class);
    List<User> users = theQuery.getResultList();
        
    return users;
}

【问题讨论】:

    标签: spring hibernate rest jpa


    【解决方案1】:

    尝试以这种方式更正您的查询:

    List<User> users = currentSession.createQuery(
       "select u from User u where u.phone = :phone",
       User.class
    ).setParameter( "phone", phone )
    .getResultList();
    

    请注意,正如documentation 中所述:

    尽管 HQL 不需要存在 select_clause通常最好包含一个。对于简单的查询,意图很明确,因此select_clause 的预期结果很容易推断。但对于更复杂的查询,情况并非总是如此。

    通常最好明确指定意图。即使在解析 JPQL 查询时,Hibernate 实际上也不会强制出现 select_clause,但是,对 JPA 可移植性感兴趣的应用程序应该注意这一点。

    【讨论】:

    • setParameter 是缺失的部分,它表示参数在不存在之前未绑定。我在网上找到了它并启动并运行了它,但既然你很友好地在我面前发布了它,我会接受你的回答。谢谢斯特恩克
    • 这是我的解决方案 Session currentSession = entityManager.unwrap(Session.class); Query theQuery = currentSession.createQuery("from User where phone= :phone",User.class); theQuery.setParameter("phone", phone); List 用户 = theQuery.getResultList();
    • 请注意,包含select_clause 通常是一种很好的做法,即使 HQL 不需要它的存在。查看更新的答案。
    【解决方案2】:

    您需要改为致电theQuery.list()

    【讨论】:

    • 这个方法我也试过了,可惜结果一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2011-09-05
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多