6

我有一个一对多的关系:一个 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”!

4

1 回答 1

10

您正在尝试保存产品。该产品与一个类别相关联。所以当 JPA 保存产品时,它的类别必须已经存在,或者必须配置一个级联,以便持久化产品级联到持久化其类别。

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

于 2013-03-17T09:56:26.563 回答