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

Thymeleaf迭代器th:each无法显示数据问题求助

Spring Boot + Thymeleaf 课程表格为空问题排查

问题点1:Thymeleaf模板表达式语法错误

看你Thymeleaf代码里的这一行:

<td th:text = "${course.getInstructor().getInstructorFirstName()} + '' + course.getInstructor().getInstructorLastName" > </td>

存在两个语法问题:

  • getInstructorLastName 缺少方法调用的括号 (),语法错误会导致模板解析失败,直接跳过循环渲染
  • 字符串拼接用了空字符串 '',应该用空格 ' ' 分隔姓名,否则拼接后姓名连在一起

修正后的写法(推荐用Thymeleaf属性访问语法,更简洁):

<td th:text="${course.instructor.instructorFirstName + ' ' + course.instructor.instructorLastName}"></td>

问题点2:懒加载导致的关联对象访问异常

你的Course实体中,instructor 和 listStudent 都用了 FetchType.LAZY 懒加载:

@ManyToOne (fetch = FetchType.LAZY)
private Instructor instructor;

@ManyToMany(fetch = FetchType.LAZY)
private Set<Student> listStudent = new HashSet<>();

当Controller返回视图后,数据库Session已关闭,Thymeleaf模板中访问这些懒加载对象时会抛出 LazyInitializationException,导致模板渲染失败,表格无数据。

解决办法:

  • 推荐方案:在Service层提前加载关联对象
    在CourseRepository的查询方法中使用JOIN FETCH,一次性查询出Course和关联的Instructor:
    @Repository
    public interface CourseRepository extends JpaRepository<Course, Long> {
        @Query("SELECT c FROM Course c JOIN FETCH c.instructor WHERE c.courseName LIKE %:keyword%")
        List<Course> findCourseBycourseName(@Param("keyword") String keyword);
    }
    
  • 临时方案:开启Open Session In View(不推荐生产环境)
    在application.properties中添加:
    spring.jpa.open-in-view=true
    
    该配置会让Session保持到模板渲染完成,但可能引发性能问题。

问题点3:确认查询是否真的返回数据

检查courseService.findCourseBycourseName(keyword)是否返回有效数据,在Controller中添加日志验证:

@GetMapping("/index")
public String getCourses(Model model, @RequestParam(name="keyword", defaultValue = "") String keyword ) {
    List<Course> courses = courseService.findCourseBycourseName(keyword);
    // 打印日志确认数据量
    System.out.println("查询到的课程数量:" + courses.size());
    model.addAttribute("listCourses", courses);
    model.addAttribute("keyword", keyword);
    return "views/courses";
}

如果日志显示数量为0,说明查询逻辑或数据库数据存在问题,需要检查Repository的查询条件、数据库中是否有对应数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:40:24