关于hibernate的一对多映射

两个类:People和City

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;

}

}

package com.pk.po;

public class People {

privateintid;

 private String name;

 public int getId() {

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

 }

}

映射文件(ORM):

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>

  <property name="name"></property>

<!--

cascade="all" 表示两表相关联

-->

<setname="cityes"cascade="all">

<keycolumn="cityid"></key>

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

</set>

</class>

</hibernate-mapping>

People.hbm.xml

<?xmlversion="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>

</class>

</hibernate-mapping>

配置文件

<!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>

相关推荐