代码之家  ›  专栏  ›  技术社区  ›  Daimyo

使用spring/thymelaf遍历数据库中对象的问题

  •  0
  • Daimyo  · 技术社区  · 2 年前

    最近我开始为Splitwise创建我的克隆项目。问题是,我无法从数据库中迭代我的用户,即使他们存在并且是在控制台中编写的。

    https://github.com/DamianKwc/SplitwiseProject.git

    web和模板一样正确打开,但没有对象。这是我第一次来这里,很抱歉出现任何问题。

    1 回复  |  直到 2 年前
        1
  •  0
  •   zawarudo    2 年前

    代替

    <tr th:each="userList : ${theUsers}">
        <td th:text="${user.id_user}"></td>
        <td th:text="${user.user_name}"></td>
        <td th:text="${user.username}"></td>
    </tr>
    

    具有

    <tr th:each="theUsers : ${userList}">
        <td th:text="${theUsers.id_user}"></td>
        <td th:text="${theUsers.user_name}"></td>
        <td th:text="${theUsers.login}"></td>
    </tr>
    

    userList需要将您在控制器中分配的值与此行相匹配

    theModel.addAttribute("userList", theUsers);
    

    theUsers 是在遍历列表时用于表示每个对象的变量名。

    所有字段都需要匹配实体的字段,而不是数据库的字段。您的数据库“用户”字段被调用 "username" ,但在实体类中它是命名的 login 您需要做的是遍历实体的字段,而不是数据库字段。

    https://www.baeldung.com/thymeleaf-iteration