欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernate多对多关联--单双向

程序员文章站 2022-04-22 21:55:38
...

前几篇文章分别介绍了一对一、一对多的关联,下面我们来看下多对多的关联。多对多关联也分为单向和双向两种。

单向关联示例

Role类

public class Role {
	private int id;
	private String name;
	private Set<Function> functions=new HashSet<Function>();
	//省略get/set
}
Function类

public class Function {
	private int id;
	private String name;
	private String code;
	private String url;
	//省略get/set方法
	public Function(){
		
	}
	public Function(String name, String code, String url) {
		super();
		this.name = name;
		this.code = code;
		this.url = url;
	}
}
Role.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">
	<class name="Role">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name" />
		<!-- 多对多 -->
		<set name="functions" table="role_func" cascade="save-update">
		<!-- 表示当前类映射到关系表中的列 -->
		<key column="rid"/>
		<!-- 所对应的另一方在关系表中的列 -->
		<many-to-many column="fid" class="Function"/>
		</set>
	</class>
</hibernate-mapping>

Function.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">
	<class name="Function">
		<id name="id">
			<generator class="native">
			</generator>
		</id>
		<property name="name" />
		<property name="code"/>
		<property name="url"/>
	</class>
</hibernate-mapping>
测试类

public class HibernateTest {
	@Test
	public void testCreateDB(){
		Configuration cfg=new Configuration().configure();
		SchemaExport se=new SchemaExport(cfg);
		//第一个参数表示是否生成ddl脚本,第二个参数表示是否执行到数据库中
		se.create(true, true);
	}
	/**
	 * 保存数据
	 */
	@Test
	public void save(){
		Session session=null;
		Transaction tx=null;
		try{
			session=HibernateUtil.getSession();
			tx=session.beginTransaction();
			Function f1=new Function("用户管理", "user_mag", "userAction");
			Function f2=new Function("角色管理", "role_mag", "roleAction");
			Function f3=new Function("系统管理", "sys_mag", "sysAction");
			Function f4=new Function("权限管理", "prev_mag", "prevAction");
			Role r1=new Role();
			r1.setName("admin");
			r1.getFunctions().add(f1);
			r1.getFunctions().add(f2);
			r1.getFunctions().add(f3);
			r1.getFunctions().add(f4);
			Role r2=new Role();
			r2.setName("vip");
			r2.getFunctions().add(f1);
			r2.getFunctions().add(f2);
			session.save(r1);
			session.save(r2);
			tx.commit();
		}catch(Exception e){
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession();
		}
	}
	@Test
	public void testGet(){
		Session session=null;
		Transaction tx=null;
		try{
			session=HibernateUtil.getSession();
			tx=session.beginTransaction();
			Role role=(Role) session.get(Role.class, 1);
			System.out.println("角色名:"+role.getName());
			System.out.println("该角色所对应权限:");
			for(Iterator<Function> iter=role.getFunctions().iterator();
					iter.hasNext();){
				Function func=iter.next();
				System.out.println(func.getName());
			}
			
			tx.commit();
		}catch(Exception e){
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession();
		}
	}
}
执行testCreateDB控制台打印信息如下:

alter table role_func 
        drop 
        foreign key FK_234akokjkyam2j9tvadytgu76

alter table role_func 
        drop 
        foreign key FK_g07mqbgd657ui8qqsho6bcw01

drop table if exists Function

    drop table if exists Role

    drop table if exists role_func

    create table Function (
        id integer not null auto_increment,
        name varchar(255),
        code varchar(255),
        url varchar(255),
        primary key (id)
    )

    create table Role (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )

    create table role_func (
        rid integer not null,
        fid integer not null,
        primary key (rid, fid)
    )

    alter table role_func 
        add constraint FK_234akokjkyam2j9tvadytgu76 
        foreign key (fid) 
        references Function (id)

    alter table role_func 
        add constraint FK_g07mqbgd657ui8qqsho6bcw01 
        foreign key (rid) 
        references Role (id)
执行save控制台打印信息如下:

Hibernate: 
    insert 
    into
        Role
        (name) 
    values
        (?)
Hibernate: 
    insert 
    into
        Function
        (name, code, url) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        Function
        (name, code, url) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        Function
        (name, code, url) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        Function
        (name, code, url) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        Role
        (name) 
    values
        (?)
Hibernate: 
    insert 
    into
        role_func
        (rid, fid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role_func
        (rid, fid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role_func
        (rid, fid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role_func
        (rid, fid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role_func
        (rid, fid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role_func
        (rid, fid) 
    values
        (?, ?)

执行testGet控制台打印信息如下:

Hibernate: 
    select
        role0_.id as id1_1_0_,
        role0_.name as name2_1_0_ 
    from
        Role role0_ 
    where
        role0_.id=?
角色名:admin
该角色所对应权限:
Hibernate: 
    select
        functions0_.rid as rid1_1_0_,
        functions0_.fid as fid2_2_0_,
        function1_.id as id1_0_1_,
        function1_.name as name2_0_1_,
        function1_.code as code3_0_1_,
        function1_.url as url4_0_1_ 
    from
        role_func functions0_ 
    inner join
        Function function1_ 
            on functions0_.fid=function1_.id 
    where
        functions0_.rid=?
系统管理
用户管理
角色管理
权限管理
数据库表信息如下:

hibernate多对多关联--单双向     hibernate多对多关联--单双向    hibernate多对多关联--单双向

双向关联示例(只展示与单向关联不同的地方)

Function类

public class Function {
	private int id;
	private String name;
	private String code;
	private String url;
	private Set<Role> roles=new HashSet<Role>();
	//省略get/set方法
	public Function(){
		
	}
	public Function(String name, String code, String url) {
		super();
		this.name = name;
		this.code = code;
		this.url = url;
	}
}

Function.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">
	<class name="Function">
		<id name="id">
			<generator class="native">
			</generator>
		</id>
		<property name="name" />
		<property name="code"/>
		<property name="url"/>
		<set name="roles" inverse="true" table="role_func">
		<key column="fid"/>
		<many-to-many column="rid" class="Role"/>
		</set>
	</class>
</hibernate-mapping>

测试类

@Test
	public void testGet(){
		Session session=null;
		Transaction tx=null;
		try{
			session=HibernateUtil.getSession();
			tx=session.beginTransaction();
			Role role=(Role) session.get(Role.class, 1);
			System.out.println("角色名:"+role.getName());
			System.out.println("该角色所对应权限:");
			for(Iterator<Function> iter=role.getFunctions().iterator();
					iter.hasNext();){
				Function func=iter.next();
				System.out.println(func.getName());
			}
			System.out.println("=============");
			Function func=(Function) session.get(Function.class, 4);
			System.out.println("功能名称:"+func.getName());
			System.out.println("该功能所对应的角色:");
			for(Iterator<Role> iter=func.getRoles().iterator();iter.hasNext();){
				System.out.println(iter.next().getName());
			}
			tx.commit();
		}catch(Exception e){
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession();
		}
	}
	@Test
	public void testDelete(){
		Session session=null;
		Transaction tx=null;
		try{
			session=HibernateUtil.getSession();
			tx=session.beginTransaction();
			Role role=(Role) session.get(Role.class, 1);
			session.delete(role);
			tx.commit();
		}catch(Exception e){
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession();
		}
	}

具体执行结果在此不做展示,有兴趣的可以自己演示。