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" />

你可能感兴趣的:(hibernate)