hibernate ExportDB 编写及one2one笔记一(主键双向关联)

双向关联跟单向关联很相近,只要将IdCard的属性加入Person,将映射文件稍作修改就可以。

IdCard类

public class IdCard {
    private int id;
    private String cardNo;
    private Person person;

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCardNo() {
        return cardNo;
    }

    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }
}

IdCard.hbm.xml


mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >

package="com.cnblogs.hibernate_first">
    <class name="IdCard" table="t_idcard">
        
            class="native">
        
        
    <--再此加入one2one标签-->
        
    class>

测试程序及结果如下:

public void testLoad2(){
        Session session = null;
        try {
            session = HibernateUtils.getSession();
            session.beginTransaction();
            IdCard idCard = (IdCard)session.load(IdCard.class, 1);
            System.out.println("idCardNO = " + idCard.getCardNo());
            System.out.println("idCard.Person.name = " + idCard.getPerson().getName());
            session.getTransaction().commit();
            
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }finally{
            HibernateUtils.closeSession(session);
        }
        
    }

结果:

Hibernate: alter table t_person add constraint FKt1wqtq1hcqkcmd4vk2cmhgd1c forei
gn key (t_id) references t_idcard (t_id)
Hibernate: select idcard0_.t_id as t_id1_0_0_, idcard0_.t_cardNo as t_cardNo2_0_
0_, person1_.t_id as t_id1_1_1_, person1_.t_name as t_name2_1_1_ from t_idcard i
dcard0_ left outer join t_person person1_ on idcard0_.t_id=person1_.t_id where i
dcard0_.t_id=?
idCardNO = 123123123
idCard.Person.name = 张三

转载于:https://www.cnblogs.com/Juli/p/7704263.html

你可能感兴趣的:(hibernate ExportDB 编写及one2one笔记一(主键双向关联))