我有两个实体- User
, UserPayment
. User
以及 UserPayment
有一个 OneToMany
关系。有一个变量 setDefault
在 UserPayment
. 新的时候 UserPayment
,其 setDefault
应该设置 true
以及其他 UserPayment
特别是 User
应设置为 false
. 新建之后 UserPayment
是创建的,当坚持,我得到下面的错误。
实体用户
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Id",nullable = false,updatable = false)
private Long id;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<UserPayment> userPaymentList;
}
实体用户支付
@Entity
public class UserPayment{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private boolean defaultPayment;
@ManyToOne
@JoinColumn(name="user_id")
@JsonIgnore
private User user;
}
控制器
@RequestMapping(value = "/add",method = RequestMethod.POST)
public ResponseEntity addNewCardDetail(@RequestBody UserPayment userPayment,Principal principal) {
if(principal != null) {
String username = principal.getName();
User user = userServiceImpl.findUserByUsername(username);
userServiceImpl.uodateUserBilling(user,userPayment);
return new ResponseEntity("Your card has been successfully saved",HttpStatus.OK);
}
return new ResponseEntity("Card not saved",HttpStatus.BAD_REQUEST);
}
服务实现
@Override
public void uodateUserBilling(User user, UserPayment userPayment) {
userPayment.setDefaultPayment(true);
userPayment.setUser(user);
List<UserPayment> paymentList = user.getUserPaymentList();
for(UserPayment eachPaymnet:paymentList) {
eachPaymnet.setDefaultPayment(false);
paymentRepository.save(eachPaymnet);
}
user.getUserPaymentList().add(userPayment);
userRepository.save(user);
}
错误
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Multiple representations of the same entity [com.bookstore.domain.UserPayment#53] are being merged. Detached: [com.bookstore.domain.UserPayment@6ea664ae]; Managed: [com.bookstore.domain.UserPayment@790e8792]; nested exception is java.lang.IllegalStateException: Multiple representations of the same entity [com.bookstore.domain.UserPayment#53] are being merged. Detached: [com.bookstore.domain.UserPayment@6ea664ae]; Managed: [com.bookstore.domain.UserPayment@790e8792]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
2条答案
按热度按时间ifmq2ha21#
错误发生在
uodateUserBilling()
,因为坚持的时候已经坚持了UserPayment
您再次将其添加到列表中user.getUserPaymentList().add(userPayment);
.添加UserPayment
只有当它是一个新的条目,否则不要添加它。请尝试下面的代码jjhzyzn02#
试着纠正你的错误
uodateUserBilling
按以下方式: