Sathish Kumar
Sathish Kumar

Reputation: 41

Multiple representations of same entity in spring boot

I have to update the three tables at the same time. When I hit from the postman all the tables are saved successfully but while I try to update, it throws the catch exception like multiple representations of the same entity.

EmployeeDetails

public class EmployeeDetails implements Serializable{   
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Column(name = "user_id", unique = true, length = 11, nullable = false) 
private Integer userId;         
    //other variable

@OneToOne(mappedBy="user",cascade =  CascadeType.ALL)   
private EmployeeAdditionalinfo userAdditionalInfo;
@OneToMany(mappedBy="user",cascade = CascadeType.ALL)
private Set<EducationDetails> educationDetail;
 //getter and setter
}

EmployeeAdditionalinfo

public class EmployeeAdditionalinfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_additional_info_id", unique = true, length = 11, nullable = false)
private Integer userAdditionalInfoId;

//other variable
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "user_id")
private EmployeeDetails user;

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "address_id")
private EmployeeAddress address;
//getter or setter }

Education details

public class EducationDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "s_no", unique = true, length = 10, nullable = true)
private Integer sno;

//variable
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "user_id")
private EmployeeDetails user;

//getter and setter }

Error

org.springframework.dao.InvalidDataAccessApiUsageException: Multiple representations of the same entity [com.icore.Payroll.Attendance.Entity.EmployeeDetails#379] are being merged. Detached: [EmployeeDetails [userId=379, userName=user name, firstName=Ganesh1, lastName=Babu, middleInitial=Middle, email=Email, password=passwo, ......]]

Upvotes: 0

Views: 1181

Answers (1)

Roberto Canini
Roberto Canini

Reputation: 349

I think you must configure the cascading only in one side of relation.

Currently you are triggering all types of cascade from EmployeeDetails to a Set of EducationDetails and then back again to EmployeeDetails due to cascade configuration inside EducationDetails entity.

This makes sense because the error says that we have two different representation (instance) of same entity, one inside the persistence context you are trying to flush and the other one retrieved during last cascade.

You can try removing last one configuration and eventually manage it manually.

Upvotes: 0

Related Questions