You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot+Thymeleaf 表格中外键关联分类字段的匹配显示问题

解决方案

问题根源

你当前的HTML代码在每个产品行内遍历了全部分类列表,所以每个产品行都会输出所有分类的标题,才会出现UI显示异常的问题。实际上你已经在Produit实体类中配置了和Categorie的多对一关联,无需额外遍历全部分类列表,直接取每个产品关联的分类字段即可。

实现步骤

  1. 后端查询调整(避免懒加载异常)
    首先确保你查询产品列表时,已经关联加载了对应的分类对象,避免懒加载导致取不到分类数据。可以在ProduitRepository中自定义关联查询方法:
public interface ProduitRepository extends JpaRepository<Produit, Integer> {
    // 关联查询加载关联分类,避免懒加载异常
    @Query("SELECT p FROM Produit p JOIN FETCH p.categorie")
    List<Produit> findAllWithCategorie();
}

在Controller层调用该方法查询产品列表,再存入模型返回前端即可。

  1. 前端Thymeleaf代码修改
    删除原有遍历全部分类的代码块,直接读取每个产品自身关联的分类标题即可,优化后的完整表格代码如下:
<table class="table align-middle mb-0">
    <thead>
        <tr>
            <th>Id</th>
            <th>Nom</th>
            <th>Prix</th>
            <th>Titre</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="produits :${ListeProduit}">
            <th scope="row" th:text="${produits.id}"></th>
            <td th:text="${produits.nom}"></td>
            <td th:text="${produits.prix}"></td>
            <!-- 直接取产品关联的分类标题,加空值判断避免空指针异常 -->
            <td th:text="${produits.categorie?.titre ?: '未分类'}"></td>
            <td>
                <button type="button" class="btn btn-light btn-sm">Modifier</button>
                <button type="button" class="btn btn-light btn-sm">Supprimer</button>
            </td>
        </tr>
    </tbody>
</table>

说明

上述代码中?.是Thymeleaf的安全导航运算符,当产品没有关联分类时不会抛出空指针异常,会直接显示后面配置的默认值未分类,你可以根据自己的需求调整默认值。

内容的提问来源于stack exchange,提问作者Mohamed Tajouri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:57:02