2 개의 엔티티 User
가 UserPayment
있습니다. , . User
및 UserPayment
이 OneToMany
관계를. 에 변수 setDefault
가 UserPayment
있습니다. 때 새로운 UserPayment
자사가 setDefault
설정해야합니다 true
및 다른 UserPayment
특정의 User
로 설정해야합니다 false
. new 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)