赞
踩
在利用Spring boot data JPA进行表设计的时候,表对象之间经常存在各种映射关系,如何正确将理解的映射关系转化为代码中的映射关系是关键之处。
举例:在公司的权限管理中,存在公司表、部门表、员工表。
一对多或多对一,用外键关联,若未设置级联删除,则删除被控方记录的时候会有外键约束。
@Entity
@Table(name = "costume_all_id")
public class AllId extends AbstractEntity {
private static final long serialVersionUID = 1L;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "costume_member_fk")
private Member member;// 用户表外键
}
@Entity
@Table(name = "costume_organization")
public class Organization extends AbstractEntity {
private static final long serialVersionUID = 1L;
@Column(nullable = false, length = 50)
private String name; // 组织名称
@OneToMany(mappedBy = "organization")
private Set<Department> departmentSet; // 部门集合
}
@Entity
@Table(name = "costume_department")
public class Department extends AbstractEntity {
private static final long serialVersionUID = 1L;
@Column(nullable = false, length = 50)
private String name; // 部门名称
@ManyToOne(optional = false)
private Organization organization; // 组织外键
@ManyToMany
private Set<Member> memberSet; // 用户表外键
public Organization getOrganization() {
return organization;
}
@JsonBackReference
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
@Entity
@Table(name = "costume_member")
public class Member extends AbstractEntity {
private static final long serialVersionUID = 1L;
@Column(nullable = false, length = 20)
private String name;
@ManyToMany
@JoinTable(joinColumns = { @JoinColumn(name = "member_id") }, inverseJoinColumns = {
@JoinColumn(name = "department_id") }) //被控方表字段名
private Set<Department> departmentSet; // 部门表外键
public Set<Department> getDepartmentSet() {
return departmentSet;
}
@JsonBackReference
public void setDepartmentSet(Set<Department> departmentSet)
{
this.departmentSet = departmentSet;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。