关于hibernate的多对一映射
两个类:
City和People两个类
package com.pk.po;
public class People {
privateintid;
privateStringname;
privateCitycity;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicCitygetCity(){
returncity;
}
publicvoidsetCity(Citycity){
this.city=city;
}}
package com.pk.po;
public class City {
privateintid;
privateStringname;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
}相关的映射文件
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"cascade="all"></many-to-one>
</class>
<!--此处用的是两个表相关联,只要保存一个表中的数据,也会影响相关联的表。
如果设置了city,则也会相应保存city到相应的表中,如果没有设置,则没有设置的属性就为空.
--></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>
</class>
</hibernate-mapping>配置文件
此处连接的是MySql数据库
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>