关于hibernate的多对一、一对多双向映射

例子是city类和people类

双向关联映射:一个城市对应多个人;

多个人对应一个城市;

People.java

package com.pk.po;

public class People {

privateintid;

privateStringname;

privateCitycity;

publicCitygetCity(){

returncity;

}

publicvoidsetCity(Citycity){

this.city=city;

}

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

 }

}

City.java

package com.pk.po;

import java.util.Set;

public class City {

privateintid;

privateStringname;

privateSetcityes;

publicSetgetCityes(){

returncityes;

}

publicvoidsetCityes(Setcityes){

this.cityes=cityes;

}

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

}

ORM映射文件:

People.hbm.xml

<?xml version="1.0"?>

<!DOCTYPEhibernate-mappingPUBLIC

"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mappingpackage="com.pk.po">

<classname="People">

<idname="id">

<generatorclass="native"></generator>

</id>

<propertyname="name"></property>

<many-to-onename="city"column="cityid"></many-to-one>

</class>

</hibernate-mapping>

City.hbm.xml

<?xml version="1.0"?>

<!DOCTYPEhibernate-mappingPUBLIC

"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mappingpackage="com.pk.po">

<classname="City">

<idname="id">

<generatorclass="native"></generator>

</id>

<propertyname="name"></property>

  <set name="cityes" cascade="all" >

  <!--

  在一对多时,在多的一方所产生的列的名称,应与多对一时的列的名字是相同的

  -->

<keycolumn="cityid"></key>

<one-to-manyclass="People"/>

</set>

</class>

</hibernate-mapping>

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/HibernateConfigurationDTD3.0//EN"

 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<propertyname="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_hql</property>

<propertyname="hibernate.connection.username">root</property>

<propertyname="hibernate.connection.password">root</property>

<propertyname="show_sql">true</property>

<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>

<mappingresource="com/pk/po/City.hbm.xml"/>

<mappingresource="com/pk/po/People.hbm.xml"/>

</session-factory>

</hibernate-configuration>

相关推荐