Hibernate基数映射关系

Hibernate基数映射关系

一、基数映射——一对一关系映射

  每个账户对应一个地址的数据库关系为例:

1、SQL脚本:
    -- 一对一(唯一外键)
    drop table t_addr;
    drop table t_act;
    create table t_act(
       id int primary key auto_increment,
       actNo varchar(50) not null unique,
       passwd varchar(50) not null,
       balance double
    );

    create table t_addr(
       id int primary key auto_increment,
       pro varchar(50) not null,
       city varchar(50) not null,
       aid int unique,
       foreign key(aid) references t_act(id)
    );

    select * from t_act;
    select * from t_addr;

2、pojo源码创建
      1.Account类
    public class Account {
        private int id;
        private String actNo;
        private String passwd;
        private double balance;    
        private Address addr;//关联属性(体现外键--关系)
        public Account() {
            super();
        }
        public Account(String actNo, String passwd, double balance) {
            super();
            this.actNo = actNo;
            this.passwd = passwd;
            this.balance = balance;
        }
       //所有的get/set方法
    }

 2.Address类
    public class Address {
        private int id;
        private String pro;
        private String city;    
        private Account act;
        public Address() {
            super();
        }
        public Address(String pro, String city) {
            super();
            this.pro = pro;
            this.city = city;
        }
       //所有的get/set方法
    }

3、配置文件

1.Account.hbm.xml
    <hibernate-mapping>
       <class name="com.hibernate.one2one.Account" table="t_act">   
          <id name="id" >
        <generator class="native"></generator>
          </id>     
          <property name="actNo" unique="true" not-null="true"></property>
          <property name="passwd" not-null="true"></property>
          <property name="balance"></property>      
          <!-- 关联关系 -->      
          <one-to-one name="addr"
                  cascade="all"
                  property-ref="act"></one-to-one>
       </class>
    </hibernate-mapping>

2.Address.hbm.xml
    <hibernate-mapping>
       <class name="com.hibernate.one2one.Address" table="t_addr">   
          <id name="id" >
        <generator class="native"></generator>
          </id>    
          <property name="pro"  not-null="true"></property>
          <property name="city"  not-null="true"></property>      
          <!-- 关联关系 -->
          <many-to-one name="act"
                    column="aid"
                    unique="true"
                    cascade="all"></many-to-one>
       </class>
    </hibernate-mapping>

4、APP测试方法
    Session s = HibernateSessionFactory.getSession();
    Transaction tr = s.beginTransaction();        
    ......(略)
    s.delete(act);
    tr.commit();

二、基数映射——一对多

  一个班级拥有多个学生为例:

 

三、基数映射——多对多

  多个学生选课,每个学生可选多门课为例:

 

posted @ 2015-07-31 12:19  LiuZhenYou  阅读(517)  评论(0编辑  收藏  举报