【发布时间】:2021-01-18 15:11:03
【问题描述】:
我正在开发一个非常小的应用程序,其中包含 3 个实体类。
1.类别。 2.产品。 3.用户
关系:-
a. 用户和产品之间的 OneToMany。
b. 类别和产品之间的 OneToMany 和 ManyToOne,即一个类别可以有多个产品,多个产品可以属于同一个类别。
实体类如下所示:-
用户实体:-
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String lastname;
private String email;
private String password;
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.EAGER)
private Set<Products> products;
//getter and setter
}
产品实体:-
@Entity
public class Products {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String productname;
private String cost;
@ManyToOne(cascade = {CascadeType.MERGE,CascadeType.PERSIST},
fetch = FetchType.LAZY)
private Category category;
//getter and setters
}
类别实体:-
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(mappedBy = "category",
cascade = {CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.EAGER)
private List<Products> products;
//getter and setters
}
将用户与数据库中的产品合并的方法:-
@GetMapping("/cart")
public String Cart(Model model){
model.addAttribute("cart",productsSet);
System.out.println(productsSet);//At this stage in console I am able to see products added in set
User user = userRepository.findById(1);//hard coded for now.
user.setProducts(productsSet);
userService.saveUserProducts(user);//saveUserProducts() method in shown below.
productsSet.clear();
return "mycart";
}
saveUserProducts() :-
@Override
@Transactional
public void saveUserProducts(User user) {
entityManager.merge(user);
}
但是当我运行程序时,我在控制台中看到以下异常:-
java.lang.IllegalStateException: Multiple representations of the same entity [com.demo.shopping.com.Entity.Products#2] are being merged. Detached: [Products{id=2, productname='p2', cost='200'}]; Detached: [Products{id=2, productname='p2', cost='200'}]
我找到了一篇关于堆栈溢出的文章,但它不适合我的情况。(java.lang.IllegalStateException: Multiple representations of the same entity with @ManyToMany 3 entities)。除此之外,我没有得到任何相关的东西。
请帮助我,让我知道如何处理这种情况。希望有人会提供帮助。 提前致谢。
【问题讨论】:
标签: java spring-boot jpa spring-data-jpa