我在Employee实体和Task实体之间有一个关系,但是当我在仓库中插入数据时,或者当我在Postman中获取数据时,它没有出现,我认为问题在于关系。
它们之间的关系是:一个员工至少有一个任务。
这是员工实体:
@Entity
@Data
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotEmpty(message = "Please enter the employee name!")
private String employeeName;
private Integer employeeNumber;
@Embedded
private Address address;
@ManyToMany
@JoinTable(
name = "task_employee",
joinColumns = @JoinColumn(name = "employee_id"),
inverseJoinColumns = @JoinColumn(name = "task_id")
)
private List<Task> tasks;
public Employee(String employeeName, Integer employeeNumber, Address address) {
this.employeeName = employeeName;
this.employeeNumber = employeeNumber;
this.address = address;
}
public Employee() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Integer getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(Integer employeeNumber) {
this.employeeNumber = employeeNumber;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
}
字符串
任务实体:
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer taskId;
@NotEmpty(message = " Please Enter the Task name!")
private String name;
@ManyToMany(mappedBy = "tasks")
private List<Employee> employees;
public Task() {
}
public Task(String name) {
this.name = name;
employees = new ArrayList<>();
}
public Integer getTaskId() {
return taskId;
}
public void setTaskId(Integer taskId) {
this.taskId = taskId;
}
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;
}
}
型
这是我在Postman中发送GET Employee时出现的内容:
{
"id": 3,
"employeeName": "fahad",
"employeeNumber": 23,
"address": {
"street": "salah",
"city": "Jeddah",
"state": "makkah",
"postalCode": "m1"
},
"tasks": []
}
型
2条答案
按热度按时间eiee3dmh1#
如果你想获取
Employee
和所有相关的Task
实体。你应该在Employee Repository
中创建一个自定义查询。字符串
另外,在
Task Entity
中,在private List<EmployeeEntity> employees;
字段上添加一个注解。就像这样:
型
@JsonIgnore
用于在JSON Serialization
中消除circular reference
,或者如果不想使用@JsonIgnore
,可以使用DTO projection。这就是全部。想要的结果看起来像这样(在Postman中):
的数据
s3fp2yjn2#
多对多关系的默认获取类型将类似于
fetch = FetchType.LAZY
您可以尝试此查询
字符串
要使用员工ID查询此特定员工的相关任务,请执行以下操作
并在返回时将其设置回employee对象中的
List<Task> tasks