I have the following entity persisted through h2 in a JPA spring project
public class Product implements DomainObject{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Version
private Integer version;
private String description;
private BigDecimal price;
private String imageUrl;
public Product() {
}
// getters and setters
}
I have an HTML page with a form to enter new data like this
<form class="form-horizontal" th:object="${product}"
th:action="@{/product}" method="post">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Description:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{description}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Price:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{price}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Image Url:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{imageUrl}"/>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
This is the method that's handling the post from the controller
@PostMapping("/product")
public String saveOrUpdateProduct(Product product){
productService.saveOrUpdate(product);
return "redirect:/product/"+product.getId();
}
And this is the saveOrUpdate method in the autowired service class that handles interaction with the database
private EntityManagerFactory emf;
@PersistenceUnit
public void setEmf(EntityManagerFactory emf) {
this.emf = emf;
}
@Override
public Product saveOrUpdate(Product domainObject) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Product savedProduct = em.merge(domainObject);
em.getTransaction().commit();
return savedProduct;
}
When I go to the HTML page with the form and I try to submit I have
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer';
nested exception is java.lang.NumberFormatException: For input string: "null"
Best Answer
Probably you have to annotate the param product in your controller:
Spring Javadoc for @RequestBody
Hope this helps!