假如有employee和department两张表,employee表中有字段id,name,deparmentId。department有字段id,name,请用springdata jpa实现关联关系查询功能
import javax.persistence.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(name = "department_id")
private Long departmentId;
@ManyToOne
@JoinColumn(name = "department_id", referencedColumnName = "id", insertable = false, updatable = false)
@NotFound(action= NotFoundAction.IGNORE)
@JsonIgnore
private Department department;
// 省略构造函数、getter和setter等
}
import javax.persistence.*;
import java.util.List;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department")
@NotFound(action= NotFoundAction.IGNORE)
private List<Employee> employees;
// 省略构造函数、getter和setter等
}
@NotFound(action= NotFoundAction.IGNORE) 解决关联的一方找不到报错的问题
@JsonIgnore 添加在子表对应的字段上,解决序列化时互相嵌套的问题