简体   繁体   中英

ClassCastException in CRUD operation

I am trying to do add product of the CRUD operation.At first i did it without ajax.Now changed the string method to suit ajax. when i add a product , it throws this exception

"java.lang.ClassCastException: java.lang.Integer cannot be cast to com.shop.model.Product"

Stack points to these lines of DAO and service respectively

return (Product) sessionFactory.getCurrentSession().save(product); 
return productDAO.addProduct(product);

Model

@Entity
@Table(name="PRODUCTS")
public class Product {
    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;
    @NotEmpty
    @Column(name="PRODUCT_NAME")
    private String productName;
    @NotNull
    @Min(1)
    @Column(name="PRICE")
    private BigDecimal  price;
    @NotNull
    @Min(1)
    @Column(name="QUANTITY")
    private int quantity;

    @NotEmpty
    @Column(name="description")
    private String description;

    @ManyToOne
    @JoinColumn(name = "categoryId")
    private Category category;

// setters and getters

Contoller

@RequestMapping("addproduct.html")
    public String viewaddProduct(Map model) {
        Product product = new Product();   
        model.put("product", product);
        return "addproduct";
    }

    @RequestMapping(value ="addproduct", method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Product addProduct(@RequestBody Product product,
             Map model) {
            model.put("productList", productService.listProducts());
            model.put("categoryList", categoryService.listCategories());
           return     productService.addProduct(product);

ProductDAOImpl

public Product addProduct(Product product) {
        return (Product) sessionFactory.getCurrentSession().save(product); 
    }

ProductServiceImpl

@Transactional
    public Product addProduct(Product product) {
        return productDAO.addProduct(product);
    }

JSP

<script>$(document).ready(function() {

      $('#Form').submit(function(event) {

          var productName = $('#productName').val();
          var price = $('#price').val();
          var quantity = $('#quantity').val();
          var json = { "productName" : productName, "price" : price, "quantity": quantity};

        $.ajax({
            url: $("#Form").attr( "action"),
            data: JSON.stringify(json),
            type: "POST",

            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(product) {
                var respContent = "";

                respContent += "<span class='success'>Product was created: [";
                respContent += product.productName + " : ";
                respContent += product.price + " : " ;
                respContent += product.quantity + "]</span>";

                $("#FromResponse").html(respContent);       
            }
        });

        event.preventDefault();
      });

    });</script>
<body>

<div id="FromResponse"></div> 
<h3> Form</h3>
<FONT color="blue"></FONT>
<form:form id="Form" action="addproduct.json" commandName="product" method="POST">
<table>
<tr><td>Product Name:<FONT color="red"><form:errors path="productName" /></FONT></td></tr>
<tr><td><form:input path="productName" /></td></tr>
<tr><td>Price:<FONT color="red"><form:errors path="price" /></FONT></td></tr>
<tr><td><form:input path="price" /></td></tr>
<tr><td>Quantity:<FONT color="red"><form:errors path="quantity" /></FONT></td></tr>
<tr><td><form:input path="quantity" /></td></tr>

<tr><td>Category:<FONT color="red"><form:errors path="category.cid" /></FONT></td></tr>
<tr><td><form:input path="category.cid" /></td></tr>
<tr><td>Description:<FONT color="red"><form:errors path="description" /></FONT></td></tr>
<tr><td><form:textarea path="description" cols="65" rows="10"/></td></tr>

<tr><td><input type="submit" value="Add Products" /></td></tr>
</table>
</form:form>

</body>

sessionFactory.getCurrentSession().save(product) is returning the identifier of type java.lang.Integer you are type casting it to com.shop.model.Product class hence you are getting the error.

public Serializable save(String entityName, Object object) throws HibernateException
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update" .
Parameters: object - a transient instance of a persistent class
Returns: the generated identifier

What you can do ..

sessionFactory.getCurrentSession().save(product); 
return product;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM