Issue
I am having a table in Postgress DB. Employee.
@Entity
public class Employee implements Serializable {
public Employee(){
}
public Employee(long id){
this.empID = id;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
long empID;
@Version
public Long version;
String name;
String city;
int age;
public long getEmpID() {
return empID;
}
public void setEmpID(long empID) {
this.empID = empID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@OneToOne(orphanRemoval=true)
@Cascade(CascadeType.ALL)
BankAccount bankAccount;
public BankAccount getBankAccount() {
return bankAccount;
}
public void setBankAccount(BankAccount bankAccount) {
this.bankAccount = bankAccount;
}
@OneToMany(fetch = FetchType.EAGER)
@Cascade(CascadeType.ALL)
Collection<Project> projects;
public Collection<Project> getProjects() {
return projects;
}
public void setProjects(Collection<Project> projects) {
this.projects = projects;
}
}
Here is my Employee Service Update function.
public Employee updateEmployee(Employee employee){
employee.setName("Updated name");
employeeRepository.save(employee);
return employee;
}
Request Data: JSON Request Method:PUT
{
"empID":"1",
"name":"New",
"city":"Agra"
}
Above service function is working fine when request is provided with empID , it's updating the same record.
But Problem started when @Version annotation is included in Employee Domain, it's creating new row on every request, Kindly suggest what is going wrong??
Solution
I am not sure how you can insert multiple rows with same empID
but anyway.
If you send your PUT request with @Version field in your Domain class. When @Versio
n is null
it will be treated as a new entry and will be inserted.
{
"empID":"1",
"name":"New",
"city":"Agra"
}
Try sending a value for version in your PUT request.
{
"empID":"1",
"name":"New",
"city":"Agra",
"version":"0"
}
Answered By - shazin