1.Hibernate关联映射-一对一(主外键,单双方向):
一, 单向外键一对一(many-to-one)
1,主表:Account : (省略get,set方法)
private Integer id;
private String name;
private Address address; //引用从表,
从表:Address(省略get,set方法)
private int id;
private String address;
2,配置文件
在Account.hbm.xml中
<many-to-one name="address" column="address_id" unique="true">
many-to-one>
二, 单向主键一对一(one-to-one)
1,主表:IDCard(省略get,set方法)
private Integer id;
private String no;
private Citizen citizen;//引用从表对象
从表:Citizen(省略get,set方法)
private int id;
private String name;
2,配置文件
在IDCard.hbm.xml中,
<id name="id">
<generator class="foreign">
<param name="property">citizenparam>
generator>
id>
<one-to-one name="citizen" constrained="true">one-to-one>
三,双向外键一对一
1,主表:Account : (省略get,set方法)
private Integer id;
private String name;
private Address address; //引用从表,
从表:Address(省略get,set方法)
private int id;
private String address;
private Account account;//引用主表
2,配置文件(在单向的基础上添加)
(1)在Account.hbm.xml中(主)
<many-to-one name="address" column="address_id" unique="true">many-to-one>
(2)在Address.hbm.xml中(从)
四, 双向主键一对一
1,主表:IDCard(省略get,set方法)
private Integer id;
private String no;
private Citizen citizen;//引用从表对象
从表:Citizen(省略get,set方法)
private int id;
private String name
private IDCard idCard;//引用主表对象
2,配置文件(在单向的基础上添加)
(1)在IDCard.hbm.xml中
<id name="id">
<generator class="foreign">
<param name="property">citizenparam>
generator>
id>
<one-to-one name="citizen" constrained="true">one-to-one>
(2)在Citizen.hbm.xml中
<one-to-one name="idCard" />
2.hibernate 关联映射 双向多对一(一对多):
1,实体类
(1)Address(多端)(get,set方法省略)
private int addressid;
private String addressinfo;
private User user;//引用关联实体
(2)User(一端)(get,set方法省略)
private int userid;
private String name;
private String password;
private Set address;//引用集合属性
2,配置文件
Address.hbm.xml文件中
<hibernate-mapping>
<class name="com.john.hibernate.entity.Address" table="t_address_tab">
<id name="addressid" type="int">
<column name="address_id" />
<generator class="identity" />
id>
<property name="addressinfo" type="java.lang.String">
<column name="address_info" />
property>
<many-to-one name="user" class="com.john.hibernate.entity.User" fetch="join">
<column name="user_id" />
many-to-one>
class>
hibernate-mapping>
在User配置文件中:
<hibernate-mapping>
<class name="com.john.hibernate.entity.User" table="t_user_tab">
<id name="userid" type="int">
<column name="user_id" />
<generator class="identity" />
id>
<property name="name" type="java.lang.String">
<column name="name" />
property>
<set name="address" table="address" inverse="true" lazy="true">
<key>
<column name="user_id" />
key>
<one-to-many class="com.john.hibernate.entity.Address" />
set>
class>
hibernate-mapping>
3.HIbernate多对多简单总结:
多对多(Set):