今天我们来讲讲多对多
多对多关系是关系数据库中两个表之间的一种关系, 该关系中第一个表中的一个行可以与第二个表中的一个或多个行相关。
若有不恰,请斧正
第一步:数据库
今天我们建三个数据库
分别有:角色表(roles),联系表(u_r),人物表(users)
第二步;entity
主表
public class Users {
private int uid;
private String uname;
private Set<Roles>roles=new HashSet<Roles>();
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Set<Roles> getRoles() {
return roles;
}
public void setRoles(Set<Roles> roles) {
this.roles = roles;
}
public Users(int uid, String uname, Set<Roles> roles) {
super();
this.uid = uid;
this.uname = uname;
this.roles = roles;
}
public Users( String uname, Set<Roles> roles) {
super();
this.uname = uname;
this.roles = roles;
}
public Users( String uname) {
super();
this.uname = uname;
}
public Users( ) {
}
}
从表
public class Roles {
private int uid;
private String mane;
private Set<Users> user=new HashSet<Users>();
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getMane() {
return mane;
}
public void setMane(String mane) {
this.mane = mane;
}
public Set<Users> getUser() {
return user;
}
public void setUser(Set<Users> user) {
this.user = user;
}
public Roles(int uid, String mane, Set<Users> user) {
this.uid = uid;
this.mane = mane;
this.user = user;
}
public Roles( String mane, Set<Users> user) {
this.mane = mane;
this.user = user;
}
public Roles( String mane) {
this.mane = mane;
}
public Roles() {
}
}
第三步;映射文件
user的映射文件
<?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 2017-11-5 14:35:33 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.entity.Users" table="USERS">
<id name="uid" type="int">
<column name="UID" />
<generator class="native" />
</id>
<property name="uname" type="java.lang.String">
<column name="UNAME" />
</property>
<set name="roles" table="u_r" cascade="save-update">
<key column="uid"></key>
<many-to-many class="com.entity.Roles" column="rid"/>
</set>
</class>
</hibernate-mapping>
roles的映射文件
<?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 2017-11-5 14:35:33 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.entity.Roles" table="ROLES">
<id name="uid" type="int">
<column name="UID" />
<generator class="native" />
</id>
<property name="mane" type="java.lang.String">
<column name="MANE" />
</property>
<set name="user" table="u_r" >
<key column="rid"></key>
<many-to-many class="com.entity.Users" column="uid" />
</set>
</class>
</hibernate-mapping>
第四步 cfg.xml
<mapping resource="com/entity/Users.hbm.xml"/>
<mapping resource="com/entity/Roles.hbm.xml"/>
草图一份