`

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>

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics