美文网首页
hibernate映射----多对多关联映射

hibernate映射----多对多关联映射

作者: Mango_lxh | 来源:发表于2018-09-10 09:17 被阅读0次

1、多对多关联映射单向

image.png
在t_user_role表中

userid:外键,参照t_user表中的主键
roleid:外键,参照t_role表中的主键
userid和roleid:共同构成t_user_role表的联合主键

一般的设计中,多对多关联映射,需要一个中间表
Hibernate会自动生成中间表
Hibernate使用many-to-many标签来表示多对多的关联
多对多的关联映射,在实体类中,跟一对多一样,也是用集合来表示的

具体映射方式:
<set name="roles" table="t_user_role">
<key column="userid"/>
<many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/>
</set>
User类
  public class User {
    private int id;
    private String name;
    private Set roles; 
     关联映射
<class name="com.bjsxt.hibernate.User" table="t_user">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="roles" table="t_user_role">
<key column="userid"/>
<many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/>
</set>
</class>
Role类
public class Role {
    private int id;
    private String name;
  关联映射
class name="com.bjsxt.hibernate.Role" table="t_role">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
生成的SQL语句如下
create table t_role (id integer not null auto_increment, name varchar(255), primary key (id))
create table t_user (id integer not null auto_increment, name varchar(255), primary key (id))
create table t_user_role (userid integer not null, roleid integer not null, primary key (userid, roleid))
alter table t_user_role add index FK331DEE5FDC0ABE1 (userid), add constraint FK331DEE5FDC0ABE1 foreign key (userid) references t_user (id)
alter table t_user_role add index FK331DEE5F86B5677 (roleid), add constraint FK331DEE5F86B5677 foreign key (roleid) references t_role (id)
多对多关联映射双向
image.png
Role类
public class Role {
private int id;
private String name;
private Set users;
. . . . . .
关联映射
<class name="com.bjsxt.hibernate.Role" table="t_role">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="users" table="t_user_role" order-by="userid">
<key column="roleid"/>
<many-to-many class="com.bjsxt.hibernate.User" column="userid"/>
</set>
</class>
User类
public class User {
    private int id; 
    private String name;
    private Set roles; 
       . . . . . .
关联映射
<class name="com.bjsxt.hibernate.User" table="t_user">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="roles" table="t_user_role">
<key column="userid"/>
<many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/>
</set>
</class>

相关文章

网友评论

      本文标题:hibernate映射----多对多关联映射

      本文链接:https://www.haomeiwen.com/subject/bomjgftx.html