SpringBoot JPA 中的实体映射错误。实体正在创建,但未添加 foreign_key
Error in Entity Mapping in SpringBoot JPA. Entities are creating but foreign_key is not added
我正在学习 SpringBoot,为此我试图在一个问题的帮助下实现我学到的东西。
这是基本问题:
我们有 2 个实体:
Team: id, name Developer: id, team_id, name, phone number
Create team API : This api takes in a team and a list of developers to be mapped with this team, and is expected to create the corresponding entries in the database.
Sample request: {"team": {"name": "claims"}, "developers": [{"name": "someone", "phone_number": "9999999999"}, {"name": "somebody", "phone_number": "9111111111"}]}
我使用了这些实体:
**Employee.java**
package com.PagerDuty.PagerDutyManager.Employee;
import com.PagerDuty.PagerDutyManager.Team.Team;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
import javax.validation.constraints.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@NotBlank(message="Invalid Name")
private String name;
@Column(columnDefinition="varchar(10)", unique = true)
@NotBlank(message = "Phone_number Number Required!")
@Pattern(regexp="(^$|[0-9]{10})", message="Invalid Phone_number Number")
private String phone_number;
@ManyToOne
@JoinColumn(referencedColumnName = "id")
@JsonBackReference
private Team team;
public Employee(){}
public Employee(Long id,
@NotNull @NotBlank(message = "Invalid Name") String name,
@NotBlank(message = "Phone_number Number Required!") @Pattern(regexp = "(^$|[0-9]{10})", message = "Invalid Phone_number Number") String phone_number, String teamId) {
this.id = id;
this.name = name;
this.phone_number = phone_number;
this.team = new Team(teamId, "");
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", phone_number='" + phone_number + '\'' +
", team=" + team +
'}';
}
}
**Team.java**
package com.PagerDuty.PagerDutyManager.Team;
import com.PagerDuty.PagerDutyManager.Employee.Employee;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.List;
@Entity
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@NotBlank(message="Invalid Name")
@Column(unique = true)
private String name;
@OneToMany(cascade=CascadeType.ALL, mappedBy = "team")
private List<Employee> employees;
public Team(){}
public Team(String id,
@NotNull @NotBlank(message = "Invalid Name") String name) {
this.id = Long.parseLong(id);
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", employees=" + employees +
'}';
}
}
我已经完成了上面的示例请求,但是无法建立关系。
Employees are added successfully while adding the team.
Add team: Here RequestBody is to handle the body properly.
// Please suggest a better way of doing the requestBody Structure Handling```
**AddTeam Controller Function**
@PostMapping("/team")
public void addTeam(@RequestBody RequestCustomBody body){
System.out.println("Add team request body "+body.toString());
Team team = body.getTeam();
team.setEmployees(body.getDevelopers());
System.out.println("New Team "+team.toString());
teamService.addTeam(team);
}
**AddTeam Service Function**
public void addTeam(Team team){
teamRepository.save(team);
}
但是我只添加了 Employee 和 Team 而没有添加外键。
任何人都请帮助我我做错了什么。并且说说做事的好方法。
你需要做 body.getDevelopers().forEach(d -> d.setTeam(team))
.
为什么?在 JPA 术语中,Employee 是关系的拥有方。这是 counter-intuitive(在日常使用中可以说“一个团队 有 名员工”)。但在 JPA 中,拥有方是(在此简化)拥有外键的一方(使用关系 table 时除外)。另一面,相反,是在关系注释中具有 mappedBy
属性 的那一面。
最重要的是,您需要在 JPA 中从拥有方设置关系。你甚至可以跳过设置team.employees
,从数据库的角度来看,效果是一样的。
我正在学习 SpringBoot,为此我试图在一个问题的帮助下实现我学到的东西。
这是基本问题: 我们有 2 个实体:
Team: id, name Developer: id, team_id, name, phone number
Create team API : This api takes in a team and a list of developers to be mapped with this team, and is expected to create the corresponding entries in the database.
Sample request: {"team": {"name": "claims"}, "developers": [{"name": "someone", "phone_number": "9999999999"}, {"name": "somebody", "phone_number": "9111111111"}]}
我使用了这些实体:
**Employee.java**
package com.PagerDuty.PagerDutyManager.Employee;
import com.PagerDuty.PagerDutyManager.Team.Team;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
import javax.validation.constraints.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@NotBlank(message="Invalid Name")
private String name;
@Column(columnDefinition="varchar(10)", unique = true)
@NotBlank(message = "Phone_number Number Required!")
@Pattern(regexp="(^$|[0-9]{10})", message="Invalid Phone_number Number")
private String phone_number;
@ManyToOne
@JoinColumn(referencedColumnName = "id")
@JsonBackReference
private Team team;
public Employee(){}
public Employee(Long id,
@NotNull @NotBlank(message = "Invalid Name") String name,
@NotBlank(message = "Phone_number Number Required!") @Pattern(regexp = "(^$|[0-9]{10})", message = "Invalid Phone_number Number") String phone_number, String teamId) {
this.id = id;
this.name = name;
this.phone_number = phone_number;
this.team = new Team(teamId, "");
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", phone_number='" + phone_number + '\'' +
", team=" + team +
'}';
}
}
**Team.java**
package com.PagerDuty.PagerDutyManager.Team;
import com.PagerDuty.PagerDutyManager.Employee.Employee;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.List;
@Entity
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@NotBlank(message="Invalid Name")
@Column(unique = true)
private String name;
@OneToMany(cascade=CascadeType.ALL, mappedBy = "team")
private List<Employee> employees;
public Team(){}
public Team(String id,
@NotNull @NotBlank(message = "Invalid Name") String name) {
this.id = Long.parseLong(id);
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", employees=" + employees +
'}';
}
}
我已经完成了上面的示例请求,但是无法建立关系。
Employees are added successfully while adding the team. Add team: Here RequestBody is to handle the body properly. // Please suggest a better way of doing the requestBody Structure Handling```
**AddTeam Controller Function**
@PostMapping("/team")
public void addTeam(@RequestBody RequestCustomBody body){
System.out.println("Add team request body "+body.toString());
Team team = body.getTeam();
team.setEmployees(body.getDevelopers());
System.out.println("New Team "+team.toString());
teamService.addTeam(team);
}
**AddTeam Service Function**
public void addTeam(Team team){
teamRepository.save(team);
}
但是我只添加了 Employee 和 Team 而没有添加外键。
任何人都请帮助我我做错了什么。并且说说做事的好方法。
你需要做 body.getDevelopers().forEach(d -> d.setTeam(team))
.
为什么?在 JPA 术语中,Employee 是关系的拥有方。这是 counter-intuitive(在日常使用中可以说“一个团队 有 名员工”)。但在 JPA 中,拥有方是(在此简化)拥有外键的一方(使用关系 table 时除外)。另一面,相反,是在关系注释中具有 mappedBy
属性 的那一面。
最重要的是,您需要在 JPA 中从拥有方设置关系。你甚至可以跳过设置team.employees
,从数据库的角度来看,效果是一样的。