我想添加新的产品对象及其类别。已成功发送产品对象,但其类别(产品内部)为空。类别无法发送的错误是什么。我怎么才能修复它?@Controller中的代码。
@GetMapping("/loadForm")
public String addNewProduct(Model model){
Product theProduct = new Product();
List<Category> categories = (List<Category>) categoryService.findAll();
model.addAttribute("categories", categories);
model.addAttribute("product", theProduct);
return "addProduct";
}
@PostMapping(value="/add")
public String addProduct(@ModelAttribute("product") Product product) {
System.out.println("Checking");
productService.insert(product);
return "product";
}HTML文件中的代码是
<form th:action="@{/products/add}" th:object="${product}" method="POST">
<input type="hidden" value="100" th:field="*{productId}"/><br>
<input type="text" th:field="*{barcode}"
class="form-control mb-4 col-10" placeholder="barcode"><br><br>
<input type="text" th:field="*{createdUser}"
class="form-control mb-4 col-10" placeholder="created User"><br><br>
<input type="text" th:field="*{lastModifiedUser}"
class="form-control mb-4 col-10" placeholder="last Modified User"><br><br>
<input type="text" th:field="*{productIsService}"
class="form-control mb-4 col-10" placeholder="product Is Service"><br><br>
<input type="text" th:field="*{productName}"
class="form-control mb-4 col-10" placeholder="product name"><br><br>
<input type="text" th:field="*{productbuyingPrice}"
class="form-control mb-4 col-10" placeholder="product buying Price"><br><br>
<input type="text" th:field="*{productsellingPrice}"
class="form-control mb-4 col-10" placeholder="product selling Price"><br><br>
<input type="text" th:field="*{version}"
class="form-control mb-4 col-10" placeholder="version"><br><br>
<select th:field="*{category}"
class="form-control mb-4 col-10" placeholder="Select category">
<option th:each="tempCategory : ${categories}" th:value="${tempCategory}" th:text="${tempCategory.categoryName}"></option>
</select>
<button type="submit" class="btn btn-info col-4">Save</button>
</form>产品和类别之间的关系是多对一的。Product类中的代码
@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST,CascadeType.REFRESH})
@JoinColumn(name="category_id")
private Category category;类别类中的代码
@JsonIgnore
@OneToMany(mappedBy="category")
private List<Stock> stocks;发布于 2020-07-13 21:14:14
在您的场景中,对于一个产品,将有多个类别。映射应为oneToMany。
在Product类中:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="category_id")
Set<Category> categories;在类别类中:
@JoinColumn(name = "category_id")
@ManyToOne(cascade = CascadeType.ALL)
private Product product;发布于 2020-07-13 22:22:14
我只需将cascade和fetch添加到类别id中。我替换这个:
@JsonIgnore
@OneToMany(mappedBy="category")
private List<Stock> stocks;有了这个:
@OneToMany(fetch = FetchType.LAZY,
mappedBy="category",
cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST, CascadeType.REFRESH})
public List<Product> products;子实体中缺少级联。
https://stackoverflow.com/questions/62876379
复制相似问题