JPA级联持续错误

前端之家收集整理的这篇文章主要介绍了JPA级联持续错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一对多关系:ProductCategory可以包含许多产品.这是代码
@Entity
public class Product implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private String id;
    @Column(name="ProductName")
    private String name;
    private BigDecimal price;
    private String description;
    @ManyToOne 
    @JoinColumn(name="UserId")
    private User user;
    @ManyToOne
    @JoinColumn(name="Category")
    private ProductCategory category;
    private static final long serialVersionUID = 1L;

    public Product() {
        super();
    }   
    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }   
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }   
    public BigDecimal getPrice() {
        return this.price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }   
    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }   
    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }   
    public ProductCategory getCategory() {
        return this.category;
    }

    public void setCategory(ProductCategory category) {
        this.category = category;
    }
}


@Entity
public class ProductCategory {
    @Id
    private String categoryName;
    @OneToMany(cascade= CascadeType.ALL,mappedBy="category")
    private List<Product> products;

    public String getCategoryName() {
        return categoryName;
    }

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

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

}

这是使用2个实体的Servlet代码

String name = request.getParameter("name");
BigDecimal price = new BigDecimal(request.getParameter("price"));
String description = request.getParameter("description");
ProductCategory category = new ProductCategory();
category.setCategoryName(request.getParameter("category"));
Product product = new Product();
product.setName(name);
product.setPrice(price);
product.setDescription(description);
product.setCategory(category);
User user = userManager.findUser("Meow");
product.setUser(user);
productManager.createProduct(product);  // productManager is an EJB injected by container

这是错误

java.lang.IllegalStateException:在同步期间,通过未标记为级联的关系找到新对象PERSIST

为什么会发生这种错误?我将该字段标记为“cascade = CascadeType.All”!

解决方法

您正在尝试保存产品.此产品与一个类别相关联.因此,当JPA保存产品时,其类别必须已经存在,或者必须配置级联,以便持久保持产品级联以保持其类别.

但是你没有这样的级联.你所拥有的是一个级联,表示对某个类别进行的任何操作都会级联到其产品列表中.

原文链接:https://www.f2er.com/java/121464.html

猜你在找的Java相关文章