【问题标题】:Find multiple objects by name using Spring JPA使用 Spring JPA 按名称查找多个对象
【发布时间】:2015-11-16 09:24:02
【问题描述】:

我正在使用Spring MVCSpring Security 创建航班预订系统,在这个应用程序中,我将为一个用户保存多个预订。然后,如果用户登录系统,我想显示他们的预订详细信息。数据库中有一个用户的多条记录。这是简单的形式。 (我正在使用 Spring 4.1.6Spring security 4.0.1

<table class="table table-bordered table-hover table-striped ">
        <thead>
            <tr>
                <th>User name</th>
                <th>Operations</th>
            </tr>
        </thead>

        <tbody>
            <c:forEach items="${us}" var="user">
                <tr>
                    <td>
                        ${user.name}
                    </td>
                    <td>
                        ${user.passengers}
                    </td>
                </tr>
            </c:forEach>
        </tbody>
    </table>

这里是controller

@RequestMapping("/account/my-bookings")
public String showBookings(Model model, Principal principal){
    String name = principal.getName();
    model.addAttribute("us",reservationService.findAll(name));
    return "my-bookings";
}

这里是service class

public List<FlightReservation> findAll(String name) {
    FlightReservation flightReservation = flightReservationRepository.findByName(name);
    return findAll(flightReservation.getName());
}

这里是repository

public interface FlightReservationRepository extends JpaRepository<FlightReservation, Integer> {

    FlightReservation findByName(String name);

}

当我执行这个时,它给出了几个例外。如果数据库中有多条记录,则给出result returns more than one elements。如果数据库中只有一个用户的记录,则控制台中存在无限循环。

作为初学者,感谢您帮助我发现我做错了事,或者我需要做些什么才能将预订详细信息放入表格中?

【问题讨论】:

    标签: spring hibernate spring-mvc spring-security spring-data-jpa


    【解决方案1】:

    您的存储库方法的返回类型错误。使用列表或集合。具有单一返回类型的工作方式类似于在 JPA 查询中调用 getSingleResult,当找到多个项目时抛出异常。

    此外,当存储库返回一个值时,服务方法会反复调用自身。应该是这样实现的:

    public List<FlightReservation> findAll(String name) {
        return flightReservationRepository.findByName(name);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 2015-04-29
      • 2021-06-22
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多