一般都用注解了,这里记录下用映射文件的形式
例子:用户(User)和订单(Order)为一对多的关系,order表维护外键(user_id)
- User.hbm.xml如下
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.hibernate.entity">
<!-- 关联数据表和对象 -->
<class name="User" table="t_user">
<!-- 关联主键 -->
<id name="id" column="id">
<generator class="identity"></generator>
</id>
<!-- 关联字段 -->
<property name="username" column="username"></property>
<set name="orders" lazy="true" inverse="true" cascade="all" >
<key column="user_id"/>
<one-to-many class="Order"/>
</set>
</class>
</hibernate-mapping>
2.order.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.hibernate.entity">
<!-- 关联数据表和对象 -->
<class name="Order" table="t_order">
<!-- 关联主键 -->
<id name="id" column="id">
<generator class="identity"></generator>
</id>
<!-- 关联字段 -->
<property name="orderName" column="order_name"></property>
<many-to-one class="User" name="user" cascade="all">
<column name="user_id"/>
</many-to-one>
</class>
</hibernate-mapping>