Composite-element映射非常类似于一对多的关系映射,配置Composite-element映射,可以实现简单的一对多关系。
本例中有一个团队(team)和成员(teammembers)表,每一个team都可以拥有多个teammembers,使用Composite-element映射能够完成这种需求。
建立两个相关的数据库表:
[sql]
create table team(
id int(11) not null auto_increment,
name varchar(50) default null,
primary key(id)
)engine=innodb default charset=gbk;
[sql]
create table teammembers(
team_id int(11) default null,
name varchar(20) default null,
age int(3) default null,
teamrole varchar(20) default null
)engine=innodb default charset=gbk;
建立实体类Team.java:
[java]
package collect.composite_element;
import java.util.HashMap;
import java.util.Map;
public class Team implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private Map memebers=new HashMap();
// Constructors
/** default constructor */
public Team() {
}
/** full constructor */
public Team(String name) {
this.name = name;
}
// Property accessors
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;
}
public Map getMemebers() {
return memebers;
}
public void setMemebers(Map memebers) {
this.memebers = memebers;
}
}
建立团队成员的实体类Member.java:
[java]
package collect.composite_element;
import java.io.Serializable;
public class Member {
private String id;
private String name;
private Team team;
private String age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
}
建立一个映射文件Team.hbm.xml:
[html]
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<import class="collect.composite_element.Member" />
<class name="collect.composite_element.Team" table="team"
catalog="ssh">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="50" />
</property>
<map name="memebers" table="teammembers">
<key column="team_id"></key>
<map-key column="teamrole" type="java.lang.String"></map-key>
<composite-element class="collect.composite_element.Member">
<parent name="team" />
<property name="name" />
<property name="age"></property>
</composite-element>
</map>
</class>
</hibernate-mapping>
“design”视图:
(注:双击所有目录节点项,都会弹出”Properties”窗口,用来设置相应属性;在单击目录节点后,在右侧的属性设置窗口也可进行相应属性的设置,非常方便)
补充:软件开发 , Java ,