Spring Boot和Thymeleaf中的单表继承 [英] Single table inheritance in Spring Boot and Thymeleaf

查看:113
本文介绍了Spring Boot和Thymeleaf中的单表继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JPA中使用单表继承.

-汽车
-电动车
-汽油车

在我的百里香模板中,我通过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):在...类型的对象上找不到属性或字段"..."

只有存在属性时,才可以呈现html标签吗?

解决方案

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

首先,我在超类汽车中编写了一个方法,该方法返回null.
在我的子类E-Car中,我覆盖了返回正确值的方法.

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

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

I am using single table inheritance in JPA.

-Car
-- E-Car
-- Gasoline-Car

In my thymeleaf template, I access a list of the superclass (car) via for-each, in order to create a table with objects of both subclasses.

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

I now have the problem, that I want to access a property of a subclass, which does not exist in the other one.

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

This throws following exception:

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

Is there any way to render a html-tag, only if a property exists?

解决方案

Ok I now found a workaround:

First of all I wrote a method in the superclass car, which returns null.
In my subclass E-Car, I overwrite the method which returns the proper value.

Now every car has a method called getKWH() and I can access it through:

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

这篇关于Spring Boot和Thymeleaf中的单表继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆