Hibernate关联映射(二)一对多
一对多关联(单向)
其实一对多就是多对一的相反,所以这里我们还是使用上一篇中的实体类。
不过略有变化,是以一的一方为主控方。
Group.java
package org.jzkangta.hibernate.many2one1.entity;// Generated 2010-8-27 14:37:02 by Hibernate Tools 3.2.1.GAimport java.util.HashSet;import java.util.Set;/** * Group generated by hbm2java */public class Group implements java.io.Serializable { private int int_; private String name; private Set<User> users = new HashSet<User>(); public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } public int getInt_() { return int_; } public void setInt_(int int_) { this.int_ = int_; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
package org.jzkangta.hibernate.many2one1.entity;// Generated 2010-8-27 14:33:39 by Hibernate Tools 3.2.1.GAimport java.util.Date;/** * User generated by hbm2java */public class User implements java.io.Serializable { private Integer id; private String name; public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } }
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated 2010-8-27 14:37:02 by Hibernate Tools 3.2.1.GA --><hibernate-mapping> <class name="org.jzkangta.hibernate.many2one1.entity.Group" table="group" catalog="ibatisdb"> <id name="int_" type="int"> <column name="int" /> <generator /> </id> <property name="name" type="string"> <column name="name" length="20" /> </property> <Set name="users"> <key column="groupid_"/> <one-to-many name="code">package org.jzkangta.hibernate.many2one1.entity;// Generated 2010-8-27 14:33:39 by Hibernate Tools 3.2.1.GAimport java.util.Date;/** * User generated by hbm2java */public class User implements java.io.Serializable { private Integer id; private String name; private Group group; public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } }
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated 2010-8-27 14:33:42 by Hibernate Tools 3.2.1.GA --><hibernate-mapping> <class name="org.jzkangta.hibernate.User" table="user" catalog="ibatisdb"> <id name="id" type="java.lang.Integer"> <column name="id_" /> <generator /> </id> <property name="name" type="string"> <column name="name_" length="50" /> </property> <many-to-one name="group" column="groupid_"/> </class></hibernate-mapping>