Делаю приложение на Spring Boot с Thymeleaf и PostgreSQL. При попытке обратиться в Thymeleaf'е к свойству сущности получаю ошибку:
2023-09-18T14:48:38.476+03:00 ERROR 11172 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring6.processor.SpringSelectFieldTagProcessor' (template: "trucks" - line 46, col 17)] with root cause
org.springframework.beans.NotReadablePropertyException: Invalid property 'truck' of bean class [com.terentyev.transportation.entities.Truck]: Bean property 'truck' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
В описании ошибки и в интернете пишут, что проблема в неправильных getter'ах и setter'ах или имени переменной, но их я проверял, тем более геттеры и сеттеры сгенерированы IDE'шкой. Название свойства вроде тоже правильное. В чем ошибка? Пробовал писать truck.isTrailer
и isTrailer()
- не работает.
Представление (ошибка в 46 строке, где <td><select th:field="*{isTrailer}">
):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
table {
width: 100%;
border: 4px double black;
border-collapse: collapse;
}
th {
text-align: left;
background: #ccc;
padding: 5px;
border: 1px solid black;
}
td {
padding: 5px;
border: 1px solid black;
}
</style>
</head>
<body>
<div><form th:method="POST" th:action="@{/boss/trucks}">
<select th:name="*{searchForTrailers}">
<option th:value="false">Машины</option>
<option th:value="true">Прицепы</option>
</select>
</form></div>
<div>
<table>
<tr>
<td>ID</td>
<td>Марка</td>
<td>Модель</td>
<td>Номер</td>
<td>Тип</td>
</tr>
<tr><form th:method="POST" th:action="@{/boss/addtruck}" th:object="${truck}">
<td><input type="submit" value="Добавить"/></td>
<td><input type="text" th:field="*{make}" placeholder="Марка"/></td>
<td><input type="text" th:field="*{model}" placeholder="Модель"/></td>
<td><input type="text" th:field="*{number}" placeholder="Номер"/></td>
<td><select th:field="*{isTrailer}">
<option th:value="false">Машина</option>
<option th:value="true">Прицеп</option>
</select></td>
<td th:if="${truck.isTrailer}">
<select th:each="type : ${trailerTypes}">
<option th:value="${type}" th:text="${type.name}"></option>
<option th:action="@{/addtrailertype}">Добавить</option>
</select></td></form></tr>
<tr th:each="truck : ${trucks}">
<td th:text="${truck.id}"></td>
<td th:text="${truck.make}"></td>
<td th:text="${truck.model}"></td>
<td th:text="${truck.number}"></td>
<td th:if="${truck.isTrailer}" th:text="${truck.type}"></td>
</tr>
</table>
</div>
</body>
</html>
Сущность:
package com.terentyev.transportation.entities;
import java.util.List;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "trucks")
public class Truck {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private boolean isTrailer;
private String make;
@ManyToOne
private Type type;
private String model;
private String number;
public Truck(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isTrailer() {
return isTrailer;
}
public void setTrailer(boolean isTrailer) {
this.isTrailer = isTrailer;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Entity
@Table(name = "trailer_types")
public static class Type {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany
private List<Truck> trucks;
//private List<Type> types;
public Type(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Truck> getTrucks() {
return trucks;
}
public void setTrucks(List<Truck> trucks) {
this.trucks = trucks;
}
}
}
UPD Только сейчас заметил, что скопировал сюда не ту ошибку. Это я экспериментировал с указанием переменной. В общем выдавалась та же самая ошибка, только вместо truck
было указано isTrailer
. Да и в целом проблема решена.
isTrailer
в простоtrailer
и по новой сгенерировать геттер и сеттер к нему. ВидимоThymeleaf
ищет геттеры по какому-то иному названию, нежели сгенерированы средой разработкиEclipse
.