1.关联映射的本质:就是将关联关系映射到数据库中,关联关系指对象模型中的一个或多个引用.
2.下面列举多对一的示例:用户和组(多个用户属于一个组)多对一关联映射是最常用的一种关联映射
*User 类
package com.lzy
public class User{
private int id;
private String name;
private Group group;//持有组的引用
public User(){};
//省略set,get方法
}
*Group类
package com.lzy
public class Group{
private int id;
private String name;
//省略get,set方法
}
3.对对象进行关系映射,这也是Hibernate中比较难的一点。
(1)User.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.lzy">
<class name="User" table="t_user">
<id name="id" column="id">
<genarator class="native"/>
</id>
<property name="name" column="user_name" not-null="true"/>
<many-to-one name="group" column="groupid"/>
</calss>
</hibernate-mapping>
(2)Group.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.lzy">
<class name="Group" table="t_group">
<id name="id" column="id">
<genarator class="native"/>
</id>
<property name="name" column="group_name" not-null="true"/>
</class>
</hibernate-mapping>
4.测试
public class Test {
public static void main(String args[]){
SessionFactory sessionFactory=null;
Session session=null;
Transaction transaction=null;
sessionFactory = HibernateUtil.getSessionFactory();// 创建一个会话工厂
session = sessionFactory.openSession();// 创建一个会话实例
transaction = session.beginTransaction();// 申明一个事务
User user= new User();
Group group = new Group();
user.setName("龙一");
group.setName("中南大学");
user.setGroup(group);
try {
transaction.begin();
session.save(user);
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
}