CRUD操作中的ClassCastException

时间:2014-10-08 12:01:24

标签: ajax spring hibernate

我正在尝试添加CRUD操作的产品。首先我没有使用ajax.Now更改了字符串方法以适应ajax。当我添加产品时,它会抛出此异常

  

“java.lang.ClassCastException:java.lang.Integer无法强制转换为com.shop.model.Product”

堆栈分别指向这些DAO和服务行

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

模型

@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

位指示

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

1 个答案:

答案 0 :(得分:2)

sessionFactory.getCurrentSession().save(product)返回类型为java.lang.Integer的标识符,您将其类型转换为com.shop.model.Product类,因此您收到错误。

public Serializable save(String entityName, Object object) throws HibernateException
保留给定的瞬态实例,首先分配生成的标识符。 (或者,如果使用指定的生成器,则使用标识符属性的当前值。)如果关联与cascade="save-update"映射,则此操作会级联到关联的实例。
参数: object - 持久化类的瞬态实例
返回:生成的标识符

你可以做什么..

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