Good morning, I have a problem with adding new entity with reference to another entity by html selector. Generally it works for String and int value but not for another object. I use this html:
<form action="#" th:action="@{/addTripCommentPost}" th:object="${tripComment}"
method="POST">
<input type="text" th:field="*{comment}"
placeholder="Wpisz komentarz">
<select th:field="*{trip}">
<option th:each="tripTH : ${trips}"
th:value="${tripTH}"
th:text="${tripTH.getName()}"/>
</select>
<input type="submit" value="Dodaj">
</form>
And for the java code: @Controller public class TripController {
@Autowired
private TripService tripService;
@GetMapping("/add-trip")
public String addTrip(Model model) {
Trip trip = new Trip();
model.addAttribute("trip", trip);
return "add-trip";
}
@PostMapping("/addTripPost")
public String addTripPost(@ModelAttribute("trip") Trip trip) {
tripService.addTrip(trip);
return "redirect:/";
}
}
@Entity
public class TripComment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String comment;
@ManyToOne(optional = false)
@JoinColumn(name = "trip_id", nullable = false)
private Trip trip;
@ManyToOne(optional = false)
@JoinColumn(name = "appUser_id", nullable = false)
private AppUser appUser;
private String nameOfTrip;
}
And I reveived this error:
2022-09-13 21:40:23.985 WARN 16892 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver :
Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult:
1 errors<EOL>Field error in object 'tripComment' on field 'trip':
rejected value [Trip{name='Tirol Prestige #1', country=AUSTRIA, price=2500.0, link='xxx', startDate=2023-03-10, finishDate=2023-03-10}];
codes [typeMismatch.tripComment.trip,typeMismatch.trip,typeMismatch.com.example.skiapp.trip.Trip,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [tripComment.trip,trip];
arguments []; default message [trip]]; default message [Failed to convert property value of type 'java.lang.String'
to required type 'com.example.skiapp.trip.Trip' for property 'trip'; nested
exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [java.lang.Long] for value
'Trip{name='Tirol Prestige #1', country=AUSTRIA, price=2500.0, link='xxx', startDate=2023-03-10, finishDate=2023-03-10}';
nested exception is java.lang.NumberFormatException: For input string:
"Trip{name='TirolPrestige#1',country=AUSTRIA,price=2500.0,link='xxx',startDate=2023-03-10,finishDate=2023-03-10}"]]
Do you know what is wrong and how to fix it? Temporialy I am using a String value to catch the name and nextly I convert it in controller but if it possible I prefer to know what is wrong.