【问题标题】:How to fix to persist data relating 2 tables to database using JavaEE, servlet, jsp,EJB, JSTL如何使用 JavaEE、servlet、jsp、EJB、JSTL 修复将 2 个表关联到数据库的数据
【发布时间】:2015-06-01 06:46:40
【问题描述】:

我已经编写了添加产品的代码,但我无法将数据持久化到数据库表中。要插入数据,我需要考虑产品表和类别表。 类别表有 id 和 name 字段。产品表是我需要插入名称、价格、描述和类别ID等数据的地方,这些数据是从类别表的ID中引用的。

我认为问题的关键在于类别字段。需要用 product.setCategory(category); 设置 因为它不允许我设置 SetcategoryID 。

所以,我正在寻求帮助,或者我应该如何更正 adminservlet 中的以下代码。我已经包含了影响这个东西的代码。

更新:在整晚尝试不同的事情后解决了这个问题。您的建议和知识仍然受到欢迎,因为您的代码可能比我的代码更有效,因为我是 Java 平台的初学者。还需要解决的一件事是数据插入成功后重定向或转发响应 它不工作。

AdminServlet

else if (userPath.equals("/admin/addProduct")){


            String name = request.getParameter("name");
            Double price = Double.parseDouble(request.getParameter("price")) ;

            String description = request.getParameter("description");
            //Integer category_id = Integer.parseInt(request.getParameter("category_id")) ;
            Integer category_id = Integer.parseInt(request.getParameter("category_id")) ;

            //Category category = new Category(request.getParameter("category"););
            //String category = category(request.getParameter("category"));
                boolean validationErrorFlag;
                validationErrorFlag = validator.validateForm(name, request);
                // if validation error found, return  to same
                if (validationErrorFlag == true) {
                    request.setAttribute("validationErrorFlag", validationErrorFlag);

                }
                else {
                    try{
                    request.setAttribute("name" , name);
                    request.setAttribute("price" , price);
                    request.setAttribute("description" , description);
                    // get selected category
                    //Category category = categoryFacade.find(Integer.parseInt(categoryId));
                    request.setAttribute("category" , category_id);

                    productManager.addProduct(name, price, description, category);
                    response.sendRedirect("/admin/showProduct");
                    }
                    catch(Exception ex){
                        ex.toString();
                    }
                }    

        }

ProductManager.java

public Product addProduct(String name, Double price, String description, Category category) {

        Product product = new Product();
        product.setName(name);
        //product.setCatId();
        product.setCategory(category);
        product.setPrice(price);
        product.setDescription(description);

        em.persist(product); 
        return product;
    }

addProduct.jsp

<h1>Add Product item: </h1>


                <form id ="addProductForm" action="<c:url value='/admin/addProduct'/>" method="post">
                    <c:if test="${!empty validationErrorFlag}">

                        <p><fmt:message key="validationErrorMessage"/> </p>
                        <c:if test="${!empty nameError}"><p><fmt:message key="nameError"/></p></c:if>
                        <c:if test="${!empty categoryError}"><p><fmt:message key="categoryError"/></p></c:if>
                        <c:if test="${!empty priceError}"><p><fmt:message key="priceError"/></p></c:if>
                        <c:if test="${!empty descriptionError}"><p><fmt:message key="descriptionError"/></p></c:if>


                    </c:if>

                    <p><strong>Product Name:</strong></p>
                    <input class ="form-control" type="text" name="name" value="${param.name}">
           <p><strong>Product Category:</strong></p>
            <select id="category" name="category" class="form-control">
                    <option value="">Select</option>
            <c:forEach var="category" items="${categories}" varStatus="iter">
                <option value="${category.id}">${category.name}</option>
            </c:forEach>
            </select>
                    <p><strong>Product Price:</strong></p>
                    <input class ="form-control col-md-6" type="text" name="price">
                    <p><strong>Product details:</strong></p>
                    <textarea class ="form-control" type="textarea" name="description" rows="4">   
                    </textarea>
                    <br>
                    <p><input class ="btn-success" type="submit" value="Submit"></p>
                </form>

category.java 实体

@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
    private Collection<Product> productCollection;

Product.java 实体

 @JoinColumn(name = "category_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Category category;
    /*
    @OneToOne
    private Category categoryId;
    */
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
    private Collection<OrderedProduct> orderedProductCollection;

【问题讨论】:

    标签: jsp jakarta-ee servlets ejb jstl


    【解决方案1】:

    解决了我的问题。如果将来有人需要,这是解决方案。

    public Product addProduct(String name, Double price, String description, Integer category_id) {
            Product product = new Product();
            product.setName(name);
            //product.setCatId();
            Category category = new Category(category_id);
            product.setCategory(category);
            product.setPrice(price);
            product.setDescription(description);
    
            //em.persist(category);
            em.persist(product); 
            return product;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-06
      • 2014-06-19
      • 2013-08-13
      • 2013-05-10
      • 2013-05-06
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      相关资源
      最近更新 更多