关于hibernate的多对一映射
两个类:
City和People两个类
?
package com.pk.po;
public class People {
?private int id;
?private String name;
?private City city;
?public int getId() {
??return id;
?}
?public void setId(int id) {
??this.id = id;
?}
?public String getName() {
??return name;
?}
?public void setName(String name) {
??this.name = name;
?}
?public City getCity() {
??return city;
?}
?public void setCity(City city) {
??this.city = city;
?}
}
package com.pk.po;
public class City {
?private int id;
?private String name;
?public int getId() {
??return id;
?}
?public void setId(int id) {
??this.id = id;
?}
?public String getName() {
??return name;
?}
?public void setName(String name) {
??this.name = name;
?}
?
?
}
相关的映射文件
People.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
?"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
?"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.pk.po">
?<class name="People" >
??<id name="id">
???<generator cascade="all"></many-to-one>
?</class>
<!--?
此处用的是两个表相关联,只要保存一个表中的数据,也会影响相关联的表。
如果设置了city,则也会相应保存city到相应的表中,如果没有设置,则没有设置的属性就为空.
-->
</hibernate-mapping>
City.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
?"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
?"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.pk.po">
?<class name="City">
??<id name="id">
???<generator class="native"></generator>
??</id>
??<property name="name"></property>
?</class>
?
</hibernate-mapping>
配置文件
此处连接的是MySql数据库
Hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
?"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
?"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
?<session-factory>
??<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
??<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_hql</property>
??<property name="hibernate.connection.username">root</property>
??<property name="hibernate.connection.password">root</property>
??<property name="show_sql">true</property>
??<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
??
??
??<mapping resource="com/pk/po/City.hbm.xml"/>
??<mapping resource="com/pk/po/People.hbm.xml"/>
?</session-factory>
</hibernate-configuration>
?
?