Home > database >  i am getting a bug when i created the product and when it shows the category type it gives me a loca
i am getting a bug when i created the product and when it shows the category type it gives me a loca

Time:10-21

In the createProduct.html after i created the product, and when i go to products.html page which it will show all the products with their details, so i get in the category section a wrong value. as u can see in the page.

Products Page to show all the products that had been created by the user

Category Entity:

@Entity

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 Long getCategories_id() {
    return categories_id;
}

public void setCategories_id(Long categories_id) {
    this.categories_id = categories_id;
}

public String getCategoryName() {
    return categoryName;
}

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

public Set<Products> getProduct_category() {
    return product_category;
}

public void setProduct_category(Set<Products> product_category) {
    this.product_category = product_category;
}

Products Entity:

@Entity
@Table(name = "Products")
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(String product_name, BigDecimal product_price, Categories product_category, String product_quantity, String product_Section, String product_ExpDate) {
    this.product_name = product_name;
    this.product_price = product_price;
    this.product_category = product_category;
    this.product_quantity = product_quantity;
    this.product_Section = product_Section;
    this.product_ExpDate = product_ExpDate;
}

public Products() {

}

public long getProduct_id() {
    return product_id;
}

public void setProduct_id(long product_id) {
    this.product_id = product_id;
}

public String getProduct_name() {
    return product_name;
}

public void setProduct_name(String product_name) {
    this.product_name = product_name;
}

public BigDecimal getProduct_price() {
    return product_price;
}

public void setProduct_price(BigDecimal product_price) {
    this.product_price = product_price;
}

public Categories getProduct_category() {
    return product_category;
}

public void setProduct_category(Categories product_category) {
    this.product_category = product_category;
}

public String getProduct_quantity() {
    return product_quantity;
}

public void setProduct_quantity(String product_quantity) {
    this.product_quantity = product_quantity;
}

public String getProduct_Section() {
    return product_Section;
}

public void setProduct_Section(String product_Section) {
    this.product_Section = product_Section;
}

public String getProduct_ExpDate() {
    return product_ExpDate;
}

public void setProduct_ExpDate(String product_ExpDate) {
    this.product_ExpDate = product_ExpDate;
}

Product Controller:

    @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";
    }
}

Products.html Page to show all the products

        <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>

CreateAProduct.html Page

        <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>

Product Service layer:

    @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();
    }
}

CodePudding user response:

The Categories class is which is being used to display the value under that Category Column you see in HTML.

You either override toString():

@Entity
public class Categories {

...
...

   @Override
    public String toString() {
        return categoryName;
    }

}

Or you call the categoryName directly instead of the Object (product_category) itself:

      <td th:text="${product.product_category.categoryName}" ></td>
  • Related