I have a problem entering the date; I have a form consisting of prodcode, name and date (where the latter has been saved as a String). I try to test it with Postman by inserting the following example fields: { "prodcode": "PC001", "name": "Personal Computer", "date": "11/23/2020" }
and when I go to save it in the db I get the following error:
Data truncation: Incorrect datetime value: '23 -11-2020 'for column' data 'at row 1
This is the code of interest:
Product.java
package com.example.Model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.example.Model.Product;
@Entity
@Table(name="productprove")
public class Product {
@Id
private String prodcode;
private String name;
private String date;
public Product() {
}
public Product(String prodcode, String name) {
super();
this.prodcode = prodcode;
this.name = name;
}
public String getProdcode() {
return prodcode;
}
public void setProdcode(String prodcode) {
this.prodcode = prodcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
Controller.java
@RestController
@CrossOrigin(origins="http://localhost:4200")
@RequestMapping(value="/api")
public class Controller {
@Autowired
private Product_Service productservice;
@PostMapping("save-product")
public boolean saveProduct(@RequestBody Product product) throws IOException, ParseException {
SimpleDateFormat dateParser = new SimpleDateFormat ("dd/MM/yyyy"); //Format for input
String date=product.getDate();
java.util.Date dn = dateParser.parse(date); //Parsing the date
SimpleDateFormat dateFormatter = new SimpleDateFormat ("dd-MM-yyyy"); //Format for output
product.setDate(dateFormatter.format(dn)); //Printing the date
return productservice.saveProduct(product);
}
I would like to know if the way I thought of it is right or if other changes need to be made.
Heartfelt thanks to those who will help me
Try to use date instead of string for the date. and use @DateTimeFormat
@Entity
@Table(name="productprove")
public class Product {
@DateTimeFormat(pattern = "dd-MM-yyyy")
@Column(name = "date")
private Date date;
I hope that will works.