ssh用注解生成数据表时,实体类之间的的关系应该怎么写

时间:2022-10-21 08:19:31

多对一,一对多的关系:

@Entity
@Table(name="employee")
public class Employee implements java.io.Serializable{
@Id
private String sn;
@ManyToOne
@JoinColumn(name="identity")
private Dept dept;
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
@Column(name="name")
private String name;
@Column(name="password")
private String password;
@Column(name="status")
private String status;
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
employee里的joinColumn里的值必须要和一方实体类的id名称对应,Table(name="数据库里要生成的表名"),cloumn:是数据库里要生成的列名,记住:多对一的类型要写一方实体类的类型

@Entity
@Table(name="dept")
public class Dept implements java.io.Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer identity;
@Column(name="name")
private String name;
@OneToMany(mappedBy="dept",fetch=FetchType.LAZY,cascade=CascadeType.ALL)
private Set<Employee> emps=new HashSet(0);
public Integer getIdentity() {
return identity;
}
public void setIdentity(Integer identity) {
this.identity = identity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Employee> getEmps() {
return emps;
}
public void setEmps(Set<Employee> emps) {
this.emps = emps;
}
}
mappedBy:写一方要生成的表名,fetch=FetchType.LAZY:是延迟加载的意思,cascadeType:ALL:就是对所有的增,删,改查都在这实现

一对一关系:

@Entity
@Table(name="biz_leave")
public class Leave implements java.io.Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@JoinColumn(name="sn") //一对一,一张请假条对应一名员工
private Employee emp;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
@GeneratedValue():这里因为我用的是mysql数据库,所有这样写,其他数据库是不一样的写法,记住在写多对一,和一对一的时候,千万别出现两个实体类的id名称一样,除非这两个类不用被实现多对一和一对一的关系,否则它将分不清,你是要哪个表。