Hibernate学习(四)多对一单向关联映射2014-10-14 csdn博客 龙轩Hibernate对于数据库的操作,全部利用面向对象的思维来理解和实现的。一般的单独表的映射,相信大家都没有问题,但是对于一些表之间的特殊关系,Hibernate提供了一些独特的方式去简化它。今天就来说说多对一的关联映射。数据库中有多对一的关系,Hibernate自然也有对象的多对一的关联关系。比如用户和用户组,一个用户只属于一个组,一个组有多名用户。我们就可以说用户和用户组的关系就是多对一的关系。用对象的uml图表示一下:

在Hibernate中如何来实现呢?首先定义这两个实体类:
package com.bjpowernode.hibernate;/*** 用户组* @author Longxuan**/public class Group {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;}}package com.bjpowernode.hibernate;/*** 用户类* @author Longxuan**/public class User {private intid;private String name;private Group group;public Group getGroup() {return group;}public void setGroup(Group group) {this.group = group;}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;}}URL:http://www.bianceng.cn/Programming/Java/201410/45830.htmhibernate.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 name="foo"><property name="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</property><property name="hibernate.show_sql">true</property><!-- 设置是否显示生成sql语句 --><property name="hibernate.format_sql">false</property><!-- 设置是否格式化sql语句--><mapping resource="com/bjpowernode/hibernate/Tables.hbm.xml"/></session-factory></hibernate-configuration>