Eu tenho 3 tabelas em meu banco de dados - Booking, Restaurant e RestaurantTable. No momento, estou tentando criar uma nova reserva e uma das etapas é adicionar uma tabela. Quando tento adicionar esta tabela, ocorre o seguinte erro:
org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.persistence.Column int for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type
Não sei porque dá esse erro, já que a tabela que estou tentando adicionar não é nula (acho que pelo menos). Espero que você entenda o que quero dizer.
Minha tabela de reservas no banco de dados:
CREATE TABLE `booking` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`R_id` int(11) NOT NULL,
`date` date not null,
`start` TEXT,
`duration` float(3,1),
`amount_of_people` int,
`name` TEXT,
`contact_preference` TEXT,
`phone_number` TEXT,
`comments` TEXT,
`current_datetime` datetime default current_timestamp,
`new_date` datetime default current_timestamp,
`deleted` bool default false,
`edited` bool default false,
`table_number` int,
PRIMARY KEY (`id`),
FOREIGN KEY (`R_id`) references `restaurant`(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
Minha RestaurantTable no banco de dados:
CREATE TABLE `restaurant_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`table_size` int,
`table_number` int,
`restaurant_id` int(11),
PRIMARY KEY (`id`),
FOREIGN KEY (`restaurant_id`) references `restaurant`(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
O arquivo .jsp da tabela que estou tentando adicionar à reserva:
<body>
<jsp:include page="../fragments/menu.jsp"/>
<div id="body">
<h2>Create new booking</h2>
<form:form method="POST" modelAttribute="booking" >
<table>
<tr>
<td>Choose a table*:</td>
<td><form:select path="tableNumber">
<form:option value="" label="--- Select ---" />
<form:options items="${tables}" itemValue="tableNumber" itemLabel="tableNumber"/>
</form:select>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
<div>
<a href="/bookings">Back to List</a>
</div>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</body>
Métodos relevantes em BookingController.java:
@RequestMapping(value = "booking/create/{id}", method = RequestMethod.GET)
public String chooseTable(@PathVariable Long id, Model model) {
Booking booking = bookingService.getBooking(id);
Restaurant restaurant = booking.getRestaurant();
Set<RestaurantTable> tableSet = restaurant.getTable();
model.addAttribute("tables", tableSet);
model.addAttribute("booking", booking);
return "chooseTable";
}
@RequestMapping(value = "booking/create/{id}", method = RequestMethod.POST)
public String chooseTableAction(@PathVariable Long id, Model model) {
return "redirect:/bookings";
}
No momento, o método POST no controlador de reserva não faz nada, já que está me dando um erro antes mesmo.
Qualquer ajuda é apreciada!
O problema com seu código é que o campo tableNumber em Booking.java é do tipo int, mas em seu jsp você tem o seguinte.
<form:option value="" label="--- Select ---" />
Basicamente, isso implica que o valor do menu suspenso de seleção pode ser nulo, caso em que o Spring não tem como converter um nulo em um tipo primitivo, portanto, ele lança essa exceção no próprio carregamento da página. Existem 2 soluções possíveis para este problema:
1> Altere o valor de value = "" para usar algum número como value = "- 1" para a opção em branco e trate o -1 em sua lógica de aplicativo de acordo.
<form:option value="-1" label="--- Select ---" />
2> Outra opção é declarar o campo tableNumber como do tipo Integer em vez de int.
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras