我有一对多关系: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
解决方法
您正在尝试保存产品.此产品与一个类别相关联.因此,当JPA保存产品时,其类别必须已经存在,或者必须配置级联,以便持久保持产品级联以保持其类别.
但是你没有这样的级联.你所拥有的是一个级联,表示对某个类别进行的任何操作都会级联到其产品列表中.