我在JPA spring项目中通过h2持有以下实体
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
}
我有一个带有表单的HTML页面,可以像这样输入新数据
<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>
这是从控制器处理帖子的方法
@PostMapping("/product")
public String saveOrUpdateProduct(Product product){
productService.saveOrUpdate(product);
return "redirect:/product/"+product.getId();
}
这是处理与数据库交互的自动服务服务类中的saveOrUpdate方法
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;
}
当我使用表单转到HTML页面时,我尝试提交
无法将'java.lang.String'类型的值转换为必需类型'java.lang.Integer'; 嵌套异常是java.lang.NumberFormatException:对于输入字符串:“null”
答案 0 :(得分:1)
您可能需要在控制器中注释param产品:
@PostMapping("/product")
public String saveOrUpdateProduct(@RequestBody Product product)
@RequestBody的Spring Javadoc
@Target(value=PARAMETER)
@Retention(value=RUNTIME)
@Documented
public @interface RequestBody
/*Annotation indicating a method parameter should be bound to the body of the
web request. The body of the request is passed through an
HttpMessageConverter to resolve the method argument depending on the
content type of the request.*/
希望这有帮助!
答案 1 :(得分:0)
问题与
有关SelectedItem.OptionText
我曾经从原始的未合并产品中调用@PostMapping("/product")
public String saveOrUpdateProduct(Product product){
productService.saveOrUpdate(product);
return "redirect:/product/"+product.getId();
}
,但它还没有ID,我解决了它返回已保存的产品
product.getId()
答案 2 :(得分:0)
在您的DTO中使用@JsonIgnoreProperties(ignoreUnknown = true)