Search code examples
springhibernatespring-bootforeign-keysthymeleaf

How do i insert data in the products table from the form i've created?


The table categories and products are mapped by relation one to many and many to one.but i am getting an error like this:

Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`summer-project`.`product`, CONSTRAINT `product_category` FOREIGN KEY (`category`) REFERENCES `categories` (`category_code`) ON DELETE NO ACTION ON UPDATE NO ACTION)

Now when i submit the add product form it should add data to the products table with the foreign key from the categories table. But i am getting the sql error.

here is my addproducts form:

<form action="#" th:action="@{/products/insert}" 
                    th:object="${products}" method="POST" enctype="multipart/form-data">

        <!-- this is for the update so that the categories id will be sent along the form  -->  
        <input type="hidden" th:field="*{id}">

        <input type="text" th:field="*{productName}"
            class="form-control mb-4 col-4" placeholder="Name">
        <input type="text" th:field="*{price}"
            class="form-control mb-4 col-4" placeholder="Price">    
        <input type="text" th:field="*{specs}"
            class="form-control mb-4 col-4" placeholder="Specs">

            <!-- for drop downlist to select the category -->
        <select  th:field="*{categories}" class="form-control mb-4 col-2">
              <option value="0">Select Category</option>
                <option th:each="tempcategory:${categories}"
                 th:text="${tempcategory.categoryCode}" th:value="${tempcategory.id}" ></option>
    </select>
    <!-- for uploading the file  -->             
         <input type="file" name="file" id="file">
        <button type="submit" class="btn btn-info col-2">Add</button>
    </form>
    <a th:href="@{/products/list}">Go back to list</a>

</div>

here is my controller for insert :

 @PostMapping("/insert")
public String insertCategory(@ModelAttribute("products") Products products,
                            @RequestParam("file") MultipartFile file,
                            BindingResult result) throws IOException {




      products.setImagePath("dummy data");
      Categories categories = categoriesService.findById(products.getCategories().getId());
     categories.add(products);
     productService.insertOrUpdate(products);


//  System.out.println("-------------------"+categories.getCategoryCode()+"------------------");


    return "redirect:/products/list";   
}

here is my products class:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="product_name")
private String productName;

@Column(name="product_specs")
private String specs;

@Column(name = "image_path")
private String imagePath;

@Column(name="price")
private double price;

 @ManyToOne(fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST,CascadeType.MERGE,
 CascadeType.DETACH,CascadeType.REFRESH}) // everyThing except delete
 @JoinColumn(name="category") 
 private Categories categories;

public Products() {

}





public Products(String productName, String imagePath, double price,String specs) {
    this.productName = productName;
    this.specs = specs;
    this.imagePath = imagePath;
    this.price = price;
//  this.categories =categories;
} 
  // getters and setters

here is my categories class:

 @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="category_name")
private String categoryName;

@Column(name="image_path")
private String  imagePath;

@Column(name = "category_code")
private String categoryCode;

@OneToMany(mappedBy = "categories", cascade =
 {CascadeType.PERSIST,CascadeType.MERGE,
 CascadeType.DETACH,CascadeType.REFRESH}) // it will look for categories in  products table to create a relationship
  private List<Products> products;

 // this is for the relational mapping 
public void add(Products tempProduct) {

    if(products == null) {
        products = new ArrayList<>();
    }

    products.add(tempProduct);
    tempProduct.setCategories(this);

}
 // getters and setters

Solution

  • I figured it out need to implement Serializeable in the categories class

     @Entity
    @Table(name = "categories")
    public class Categories implements Serializable{
    
    //define fields
    // define getters and setters 
    
    }