在spring中创建实体时如何触发setter
我是spring的新手,我在spring.io网站上观看了一个代码如何工作的示例 在下面的代码中如何调用setter,如果类中没有字段在spring中创建实体时如何触发setter,spring,Spring,我是spring的新手,我在spring.io网站上观看了一个代码如何工作的示例 在下面的代码中如何调用setter,如果类中没有字段name,为什么setName()setter可以工作 import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity class Employee
name
,为什么setName()setter可以工作
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
class Employee {
private @Id @GeneratedValue Long id;
private String firstName;
private String lastName;
private String role;
Employee(String firstName, String lastName, String role) {
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
}
public Employee() {
}
public String getName() {
return this.firstName + " " + this.lastName;
}
public void setName(String name) {
String[] parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
public Long getId() {
return this.id;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public String getRole() {
return this.role;
}
public void setId(Long id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setRole(String role) {
this.role = role;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Employee))
return false;
Employee employee = (Employee) o;
return Objects.equals(this.id, employee.id) && Objects.equals(this.firstName, employee.firstName)
&& Objects.equals(this.lastName, employee.lastName) && Objects.equals(this.role, employee.role);
}
@Override
public int hashCode() {
return Objects.hash(this.id, this.firstName, this.lastName, this.role);
}
@Override
public String toString() {
return "Employee{" + "id=" + this.id + ", firstName='" + this.firstName + '\'' + ", lastName='" + this.lastName
+ '\'' + ", role='" + this.role + '\'' + '}';
}
}
控制器
@PostMapping("/employees")
ResponseEntity<?> newEmployee(@RequestBody Employee newEmployee) {
EntityModel<Employee> entityModel = assembler.toModel(repository.save(newEmployee));
return ResponseEntity //
.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) //
.body(entityModel);
}
@PostMapping(“/employees”)
ResponseEntity newEmployee(@RequestBody Employee newEmployee){
EntityModel EntityModel=assembler.toModel(repository.save(newEmployee));
返回响应性//
.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri())//
.主体(实体模型);
}
为什么setName()
setter在什么情况下工作?