更新Spring引导应用程序

时间:2016-08-08 05:48:05

标签: java spring hibernate jpa spring-boot

我在Postgress DB中有一张桌子。 雇员。

 @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;
}

}

这是我的员工服务更新功能。

 public Employee updateEmployee(Employee employee){
    employee.setName("Updated name");
    employeeRepository.save(employee);

    return employee;
}

请求数据:JSON 请求方法:PUT

{
  "empID":"1",
  "name":"New",
 "city":"Agra"
 }

当使用empID提供请求时,上述服务功能正常工作,它正在更新相同的记录。

但问题在员工域中包含@Version注释时开始,它在每个请求上创建新行,请建议出现问题?

1 个答案:

答案 0 :(得分:1)

我不知道如何使用相同的empID插入多行但是无论如何。

如果您在Domain类中使用@Version字段发送PUT请求。当@Versio n为null时,它将被视为新条目并将被插入。

{
  "empID":"1",
  "name":"New",
  "city":"Agra"
}

尝试在PUT请求中发送版本值。

{
  "empID":"1",
  "name":"New",
  "city":"Agra",
  "version":"0"
}