Hibernate数据关联关系:一对多

数据关联关系中的一对多

举例:用户和住址(一个用户可能有一个或多个住址)

1.创建用户表和住址表

---用户表----
create table person(
  pid varchar2(32) primary key,
  pname varchar2(32) not null
)
----住址表----
create table address(
  aid varchar2(32) primary key,
  name VARCHAR(50) NOT NULL ,
  zipcode VARCHAR(10) NOT NULL ,
  pid VARCHAR(32) ,
  FOREIGN KEY (pid) REFERENCES person(pid) ON DELETE CASCADE
)

 

 2.创建两个表对应的pojo类

public class Person {
             //用户id
	private String pid = "";
	//名字
	private String pname = "";
	//住址对象	
	private Set<Address> addressSet = null;
              ........................  
}

 

public class Address {
             //住址id
	private String aid = "";
	//住址地点
	private String name = "";
	//区号
	private String zipcode = "";
	//住户对象
	private Person person = null;
           ..............................
}	

 

3.建立相应的映射关系

  Person.hbm.xml

<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="包名">

    <class name="Person" table="person">
      <id name="pid" column="pid" type="string">
         <generator class="uuid.hex"/>
      </id>
      <property name="pname" column="pname" type="string"/>
     <set name="addressSet" table="address" cascade="all" inverse="true">
            <key>
				<column name="pid" length="32" />
			</key>
			<one-to-many class="Address"/>
     </set>
    </class>
    
</hibernate-mapping>

 Address.hbm.xml

<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="包名">

    <class name="Address" table="address">
      <id name="aid" column="aid" type="string">
         <generator class="uuid.hex"/>
      </id>
      <property name="name" column="name" type="string"/>
      <property name="zipcode" column="zipcode" type="string"/>
     <many-to-one name="person" class="Person">
       <column name="pid"></column>
     </many-to-one>
    </class>
    
</hibernate-mapping>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值