我得到一个错误500,而我试图显示所有的产品,存在于我的数据库中使用SpringBoot



当我创建一个产品并填写create_product.html页面中的详细信息时,当我单击添加按钮时,它应该引导我到我将显示所有产品的products .html页面,但当我转移到products .html页面时,我得到了一个错误。然而,当我检查我的数据库表时,我发现产品已被添加。

ProductController类

@Controller
public class ProductsController {

//adding the service layer of the product
@Autowired
private  ProductService productService;
@Autowired
private CategoriesRepository categoriesRepository;
public  ProductsController(ProductService productService,CategoriesRepository categoriesRepository )
{
super();
this.productService = productService;
this.categoriesRepository = categoriesRepository;
}
// models
@ModelAttribute("category")
public List<Categories> initializeCategories(){
List<Categories> categories = categoriesRepository.findAll();
return categories ;
}
@ModelAttribute("product")
public Products products()
{
return new Products();
}

/////////////////////////////////// handllers

//request to list all the products
@RequestMapping("/products/all_products")
public String listProducts(Model model)
{
model.addAttribute("product",productService.getAllProducts());
return "Products/products";
}

//request to show the form to create a product // when u are accessing the http request u will access that one coz it will show the form and then the Save method will do the action
@GetMapping("/products/new/product")
public String createProductForm(Model model)
{
//Create product object
Products product = new Products();
model.addAttribute("product",product); // product is the object from products Entityclass
return "Products/create_product";
}
//request to create/save a product
@RequestMapping(value = "/products/create_product",method = RequestMethod.POST)
public String saveProduct(@ModelAttribute("product") Products product) // Products is the name of the Entity class and creating a productObjcet from it
{
productService.saveProduct(product);
return "redirect:/products/all_products";
}
@GetMapping("/products/edit/{id}")
public String editProductForm(@PathVariable long id, Model model)
{
model.addAttribute("product",productService.getProductById(id));
return "Products/edit_product";
}
//request to update product
@RequestMapping(value = "/products/update_product/{id}",method=RequestMethod.POST)
public String updateProduct(@PathVariable Long id, @ModelAttribute("product") Products product, Model model) // model Attribute is the data taken from the html file by the user
{
//get product from the db by id
Products existingProduct = productService.getProductById(id);
existingProduct.setProduct_id(id);
existingProduct.setProduct_name(product.getProduct_name());
existingProduct.setProduct_price(product.getProduct_price());
existingProduct.setProduct_category(product.getProduct_category());
existingProduct.setProduct_quantity(product.getProduct_quantity());
existingProduct.setProduct_Section(product.getProduct_Section());
existingProduct.setProduct_ExpDate(product.getProduct_ExpDate());

//updating the product
productService.updateProduct(existingProduct);
return "redirect:/products/all_products";
}
//request to Delete product
@GetMapping("/products/delete_product/{id}")
public String deleteProduct(@PathVariable long id)
{
productService.deleteProduct(id);
return "redirect:/products/all_products";
}
}

类别实体类:

@Entity
@Data
public class Categories {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long categories_id;
private String categoryName;
@OneToMany(mappedBy = "product_category",fetch = FetchType.LAZY) //the name of the variable in the other class
private Set<Products> product_category = new HashSet<>();

public Categories(String categoryName, Set<Products> product_category) {
this.categoryName = categoryName;
this.product_category = product_category;
}
public Categories() {
}

public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
}

产品实体类:

@Entity
@Table(name = "Products")
@Data
public class Products {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long product_id;
private String product_name;
private BigDecimal product_price;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categories_id") //the name of the column in the other class and that name will be a column in the class
private Categories product_category;
private String product_quantity;
private String product_Section;
private String product_ExpDate;

public Products()
{
super();
}
public Products(String product_name, BigDecimal product_price,String product_quantity,Categories product_category ,String product_Section,String product_ExpDate) {
this.product_name = product_name;
this.product_category = product_category;
this.product_price = product_price;
this.product_quantity = product_quantity;
this.product_Section = product_Section;
this.product_ExpDate = product_ExpDate;
}

ProductService类:

@Service
public class ProductServiceImp implements ProductService {

//productRepository class
private ProductRepository productRepository;
public ProductServiceImp(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Override
public List<Products> getAllProducts() {
return this.productRepository.findAll();
}
@Override
public Products saveProduct(Products product) {
return this.productRepository.save(product);
}
@Override
public Products updateProduct(Products product) {
return this.productRepository.save(product);
}
@Override
public void deleteProduct(long id) {
this.productRepository.deleteById(id);
}
public Products getProductById(long id)
{
return productRepository.findById(id).get();
}
}

CreateProduct.html页面:

<form th:action="@{/products/create_product}" method="post" th:object="${product}">
<div class="form-group">
<label class="control-label" for="product_name"> Product Name </label> <input
id="product_name" class="form-control" th:field="*{product_name}"
required autofocus="autofocus" />
</div>
<div class="form-group">
<label class="control-label" for="product_price"> Price </label> <input
id="product_price" class="form-control" th:field="*{product_price}" required
autofocus="autofocus" />
</div>
<div class="col-1.5">
<label th:for="category"> Category </label>
<select class="form-control form-control-sm" id="category" name="product_category">
<option value=""> Select Category </option>
<option th:each = "category: ${category}"
th:value="${category.categories_id}"
th:text="${category.categoryName}"
> <!--th:field="*{product_category}"-->
</option>
</select>
</div>
<br>
<div class="form-group">
<label class="control-label" for="product_quantity"> Quantity </label> <input
id="product_quantity" class="form-control" type="text"
th:field="*{product_quantity}" required autofocus="autofocus" />
</div>
<div class="form-group">
<label class="control-label" for="product_Section"> Section </label> <input
id="product_Section" class="form-control" type="text"
th:field="*{product_Section}" required autofocus="autofocus" />
</div>
<div class="form-group">
<label class="control-label" for="product_ExpDate"> Expire Date </label> <input
id="product_ExpDate" class="form-control" type="text"
th:field="*{product_ExpDate}" required autofocus="autofocus" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>

products.html页面

<table class = "table table-striped table-bordered">
<thead class = "table-dark">
<tr>
<th> Category </th>
<th> Product Name </th>
<th> Product Price </th>
<th> Product Quantity </th>
<th> Product Section </th>
<th> Product Expiry Date </th>
<th> Edit </th>
<th> Delete </th>
</tr>
</thead>
<tbody>
<tr th:each = "product: ${product}"> <!-- this attribute to list up products  -->
<td th:text="${product.product_category}" ></td>
<td th:text="${product.product_name}"></td>
<td th:text="${product.product_price}"></td>
<td th:text="${product.product_quantity}" ></td>
<td th:text="${product.product_Section}" ></td>
<td th:text="${product.product_ExpDate}" ></td>
<td> <center> <a th:href="@{/products/edit/{id}(id=${product.product_id})}" style="color: green"> Edit </a> </center> </td>
<td> <center> <a th:href="@{/products/delete_product/{id}(id=${product.product_id}) }" style="color: red"> Delete </a> </center> </td>
</tr>
</tbody>
</table>

FullTrace错误:

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Oct 20 03:45:45 EDT 2021
There was an unexpected error (type=Internal Server Error, status=500).
No message available
java.lang.StackOverflowError
at com.mysql.cj.NativeSession.execSQL(NativeSession.java:696)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:930)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:390)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:163)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:104)
at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:710)
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:99)
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2163)
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:589)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)
at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)
at com.example.warehouseManagementSystem.Entities.Categories.hashCode(Categories.java:10)
at com.example.warehouseManagementSystem.Entities.Products.hashCode(Products.java:10)
at java.base/java.util.HashMap.hash(HashMap.java:340)
at java.base/java.util.HashMap.put(HashMap.java:612)
at java.base/java.util.HashSet.add(HashSet.java:221)

问题是您正在实体上使用Lombok中的@Data。将其移除,并以一种不会导致StackOverflowError的方式手动实现equals()hashCode。在大多数情况下,您只需要检查主键。

有关如何正确实现equals和hashcode的更多信息,请参阅https://www.wimdeblauwe.com/blog/2021/04/26/equals-and-hashcode-implementation-considerations/。

请参阅https://thorben-janssen.com/lombok-hibernate-how-to-avoid-common-pitfalls/#Avoid_Data了解为什么您应该小心使用Lombok和JPA/Hibernate。

相关内容

最新更新