【问题标题】:Single table inheritance in Spring Boot and ThymeleafSpring Boot 和 Thymeleaf 中的单表继承
【发布时间】:2017-06-11 04:51:57
【问题描述】:

我在 JPA 中使用单表继承。

-汽车
-- 电动车
-- 汽油车

在我的 thymeleaf 模板中,我通过 for-each 访问超类(汽车)的列表,以便创建一个包含两个子类对象的表。

<tr th:each="car : ${cars}" 
th:class="${not car.isECar()} ? 'electricCar' : 'notECar'">

我现在有一个问题,我想访问另一个子类中不存在的属性。

<td th:text="'kWh ' + ${car.kwh}" style="vertical-align: center;">1025 kWh</td>

这会引发以下异常:

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 6): Property or field '...' cannot be found on object of type ...

有什么方法可以渲染一个 html-tag,只有当一个属性存在的时候?

【问题讨论】:

  • 试试 th:if="${car.kwh!=null}"
  • @benkuly 不起作用,因为在另一个子类中找不到 kwh :(

标签: java jpa spring-boot thymeleaf


【解决方案1】:

好的,我现在找到了解决方法:

首先我在超类car中写了一个方法,它返回null。
在我的子类 E-Car 中,我覆盖了返回正确值的方法。

现在每辆车都有一个名为 getKWH() 的方法,我可以通过以下方式访问它:

<td th:text="${car.getKWH()} + ' kWh'" th:if="${car.getKWH()!=null}">2200 kWh</td>

【讨论】:

  • 我也有同样的问题...但是寻找更好的解决方案
猜你喜欢
  • 2021-01-11
  • 2021-09-03
  • 1970-01-01
  • 2017-07-14
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
相关资源
最近更新 更多