对象之间的关系(重要)
指的是对象间的关联关系
- 一对一
单向(主键、外键)
双向(主键、外键)
中间表(很少用) - 一对多
单向
双向 - 多对一
单向
双向 - 多对多
单向
双向
一对一
单向(主键、外键)
- 外键关联
// husband和wife husband中的wifeid 参考wife的id
@Entity
public class Husband {
private String name;
private int id;
private Wife wife;
@OneToOne
@JoinColumn(name = "wifeid")
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
}
@Entity
public class Wife {
private String name;
private int id;
@Id
@GeneratedValue
public int getId() {
return id;
}
...
}
用xml
<hibernate-mapping package="relationship">
<!--table 属性不配就是默认-->
<class name="Husband">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<many-to-one name="wife" column="wifeid" unique="true"/>
</class>
</hibernate-mapping>
- 主键关联(不重要)
@PrimaryKeyJoinColumn
<one-to-one name="studentIDCard" constrained="true"/>
双向(主键、外键)
- 主键(不重要)
- 外键
存在双向外键关联是,必设mappedby
@Entity
public class Husband {
private String name;
private int id;
private Wife wife;
@OneToOne
@JoinColumn(name = "wifeid")
public Wife getWife() {
return wife;
}
}
@Entity
public class Wife {
private String name;
private int id;
private Husband husband;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToOne(mappedBy = "wife")
public Husband getHusband() {
return husband;
}
}
xml中:
一个xml和另一个xml的配置
<many-to-one name="studentIDCard" unique="true"/>
<one-to-one name="student" property-ref="studentIDCard"/>
联合主键关联(有可能会有)
一对多
单向
双向
多对一
单向
双向
多对多
单向
双向