如何解决为什么春季数据jpa-java.lang.IllegalStateException:OneToMany关系中同一实体的多个表示形式?
1 。类别。 2 。产品。 3 。用户
关系:-
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,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,cost='200'}]
我找到了一篇有关堆栈溢出的文章,但不适合我的情况。(java.lang.IllegalStateException: Multiple representations of the same entity with @ManyToMany 3 entities)。除此之外,我没有得到任何相关的东西。
请帮助我让我知道如何处理这种情况。希望有人能帮上忙。 预先感谢。
解决方法
删除CascadeType.MERGE用户类,因为在我的程序中除了创建现有用户和产品之间的关系之外,我也没有添加新产品。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。