Hibernate关系映射:多对多关联(示例)

Hibernate关系映射:多对多关联

N-N关联映射增加一张表才完成基本映射。

与1-N映射相似,必须为set集合元素添加key子元素,指定CATEGORIES_ITEMS表中参照CATEGORIES表的外键为CATEGORIY_ID。

与1-N不同的是,建立N-N关联时,集合中的元素使用many-to-many。关于配置文件的属性的介绍,将在代码实现部分介绍。

数据库设计:

Hibernate关系映射:多对多关联(示例)_第1张图片

案例:

角色表实体类:

package com.liuyongqi.MavenHibernateDemo6.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
 * 角色表实体类
 * @author Administrator
 * @data   2018年8月7日
 * @time   上午10:52:16
 */
public class Roles implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3594387215393055820L;
	private Integer rid;									//角色编号
	private String rname;									//角色名称
	private Set usersSet=new HashSet();		//用户集合
	public Roles() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Roles(String rname) {
		super();
		this.rname = rname;
	}
	public Roles(Integer rid, String rname) {
		super();
		this.rid = rid;
		this.rname = rname;
	}
	public Integer getRid() {
		return rid;
	}
	public void setRid(Integer rid) {
		this.rid = rid;
	}
	public String getRname() {
		return rname;
	}
	public void setRname(String rname) {
		this.rname = rname;
	}
	
	public Set getUsersSet() {
		return usersSet;
	}
	public void setUsersSet(Set usersSet) {
		this.usersSet = usersSet;
	}
	@Override
	public String toString() {
		return "Roles [rid=" + rid + ", rname=" + rname + "]";
	}
	
	
}

用户实体类:

package com.liuyongqi.MavenHibernateDemo6.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
 * 用户实体类
 * @author Administrator
 * @data   2018年8月7日
 * @time   上午10:50:09
 */
public class Users implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7658139381686355418L;
	private Integer uid;									//用户编号
	private String uname;									//用户名称
	private Set rolesSet=new HashSet();		//角色集合
	public Users() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Users(String uname) {
		super();
		this.uname = uname;
	}
	public Users(Integer uid, String uname) {
		super();
		this.uid = uid;
		this.uname = uname;
	}
	public Integer getUid() {
		return uid;
	}
	public void setUid(Integer uid) {
		this.uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	
	public Set getRolesSet() {
		return rolesSet;
	}
	public void setRolesSet(Set rolesSet) {
		this.rolesSet = rolesSet;
	}
	@Override
	public String toString() {
		return "Users [uid=" + uid + ", uname=" + uname + "]";
	}
	
}

SessionFactoryUtil工具类:

package com.liuyongqi.MavenHibernateDemo6.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 提供了开启和关闭session的方法
 * @author Administrator
 * @data   2018年8月1日
 * @time   下午3:32:56
 */
public class SessionFactoryUtil {
	//ThreadLocal为每个线程提供一个单独的存储空间
	private static ThreadLocal threadLocal=new ThreadLocal();
	
	//私有化静态变量,静态变量只实例化一次
	private static SessionFactory sessionFactory;
	//实例化一次sessionFactory
	static {
		Configuration configure = new Configuration().configure();
		sessionFactory=configure.buildSessionFactory();
	}
	//私有化构造方法
	private SessionFactoryUtil() {
		
	}
	//打开session的方法
	public static Session openSession() {
		//从ThreadLocal中拿取一个session
		Session session = threadLocal.get();
		if(null==session) {
			//sessionFactory打开一个session
			session=sessionFactory.openSession();
			//把session又放入ThreadLocal中
			threadLocal.set(session);
		}
		return session;
	}
	
	//关闭资源
	public static void closeSession() {
		//从ThreadLocal中拿取一个session
		Session session = threadLocal.get();
		if(null==session) {
			if(session.isOpen()) {
				//关闭session
				session.close();
			}
			threadLocal.set(null);
		}		
	}
	
	public static void main(String[] args) {
		Session session = openSession();
		System.out.println(session);
		System.out.println("ok");
	}
	
}

Roles.hbm.xml:





    
        
            
            
        
        
            
        
        
        	
        	
        
    

Users.hbm.xml:





    
        
            
            
        
        
            
        
        
       
        	
        	
        
    

添加测试代码:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo6.entity.Roles;
import com.liuyongqi.MavenHibernateDemo6.entity.Users;
import com.liuyongqi.MavenHibernateDemo6.util.SessionFactoryUtil;

/**
 * 添加的测试类
 * @author Administrator
 * @data   2018年8月7日
 * @time   上午11:05:57
 */
public class TestSave {
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Users users1=new Users("辉辉");
		Users users2=new Users("静静");
		
		Roles roles1=new Roles("老公");
		Roles roles2=new Roles("老婆");
		Roles roles3=new Roles("儿子");
		Roles roles4=new Roles("孙子");
		
		users1.getRolesSet().add(roles1);
		users1.getRolesSet().add(roles3);
		users1.getRolesSet().add(roles4);
		users2.getRolesSet().add(roles2);
		users2.getRolesSet().add(roles4);
		
		roles1.getUsersSet().add(users1);
		roles2.getUsersSet().add(users2);
		roles3.getUsersSet().add(users1);
		roles4.getUsersSet().add(users1);
		roles4.getUsersSet().add(users2);
		
		//添加
		/*session.save(users1);
		session.save(users2);
		session.save(roles1);
		session.save(roles2);
		session.save(roles3);
		session.save(roles4);*/
		
		//级联添加
		session.save(users1);
		session.save(users2);
		
		
		transaction.commit();
		SessionFactoryUtil.closeSession();
	}

}

控制台结果:

Hibernate: 
		    insert 
		    into
		        users
		        (uname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        roles
		        (rname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        roles
		        (rname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        roles
		        (rname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        users
		        (uname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        roles
		        (rname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        users_roles
		        (rid, uid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        users_roles
		        (rid, uid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        users_roles
		        (rid, uid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        users_roles
		        (rid, uid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        users_roles
		        (rid, uid) 
		    values
		        (?, ?)

删除的测试代码:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo6.entity.Roles;
import com.liuyongqi.MavenHibernateDemo6.entity.Users;
import com.liuyongqi.MavenHibernateDemo6.util.SessionFactoryUtil;

/**
 * 删除的测试类
 * @author Administrator
 * @data   2018年8月7日
 * @time   上午11:05:57
 */
public class TestDelete {
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Users users = session.get(Users.class, 1);
		if(users!=null) {
			session.delete(users);
		}
		transaction.commit();		
		SessionFactoryUtil.closeSession();
	}

}

控制台结果:

 

Hibernate: 
				    select
				        users0_.uid as uid1_1_0_,
				        users0_.uname as uname2_1_0_ 
				    from
				        users users0_ 
				    where
				        users0_.uid=?
				Hibernate: 
				    select
				        rolesset0_.uid as uid1_2_0_,
				        rolesset0_.rid as rid2_2_0_,
				        roles1_.rid as rid1_0_1_,
				        roles1_.rname as rname2_0_1_ 
				    from
				        users_roles rolesset0_ 
				    inner join
				        roles roles1_ 
				            on rolesset0_.rid=roles1_.rid 
				    where
				        rolesset0_.uid=?
				Hibernate: 
				    delete 
				    from
				        users_roles 
				    where
				        rid=?
				Hibernate: 
				    delete 
				    from
				        users_roles 
				    where
				        rid=?
				Hibernate: 
				    delete 
				    from
				        users_roles 
				    where
				        rid=?
				Hibernate: 
				    delete 
				    from
				        roles 
				    where
				        rid=?
				Hibernate: 
				    delete 
				    from
				        roles 
				    where
				        rid=?
				Hibernate: 
				    delete 
				    from
				        roles 
				    where
				        rid=?
				Hibernate: 
				    delete 
				    from
				        users 
				    where
				        uid=?

 修改的测试代码:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo6.entity.Roles;
import com.liuyongqi.MavenHibernateDemo6.entity.Users;
import com.liuyongqi.MavenHibernateDemo6.util.SessionFactoryUtil;

/**
 * 删除的测试类
 * @author Administrator
 * @data   2018年8月7日
 * @time   上午11:05:57
 */
public class TestUpdate {
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Users users = session.get(Users.class, 5);
		if(users!=null) {
			users.setUname("辉辉2");
			session.update(users);
		}
		transaction.commit();
		SessionFactoryUtil.closeSession();
	}

}

 控制台结果:

Hibernate: 
		    select
		        users0_.uid as uid1_1_0_,
		        users0_.uname as uname2_1_0_ 
		    from
		        users users0_ 
		    where
		        users0_.uid=?
		Hibernate: 
		    update
		        users 
		    set
		        uname=? 
		    where
		        uid=?

查询的测试代码:

package test;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo6.entity.Roles;
import com.liuyongqi.MavenHibernateDemo6.entity.Users;
import com.liuyongqi.MavenHibernateDemo6.util.SessionFactoryUtil;

/**
 * 删除的测试类
 * @author Administrator
 * @data   2018年8月7日
 * @time   上午11:05:57
 */
public class TestSelect {
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Users users = session.get(Users.class, 1);	
		System.out.println(users);
		Set rolesSet = users.getRolesSet();
		for (Roles roles : rolesSet) {
			System.out.println(roles);
		}
		SessionFactoryUtil.closeSession();
	}

}

控制台结果:

 

Hibernate: 
		    select
		        users0_.uid as uid1_1_0_,
		        users0_.uname as uname2_1_0_ 
		    from
		        users users0_ 
		    where
		        users0_.uid=?
		Hibernate: 
		    select
		        rolesset0_.uid as uid1_2_0_,
		        rolesset0_.rid as rid2_2_0_,
		        roles1_.rid as rid1_0_1_,
		        roles1_.rname as rname2_0_1_ 
		    from
		        users_roles rolesset0_ 
		    inner join
		        roles roles1_ 
		            on rolesset0_.rid=roles1_.rid 
		    where
		        rolesset0_.uid=?
		Users [uid=1, uname=辉辉, rolesSet=[Roles [rid=3, rname=儿子], Roles [rid=1, rname=老公], Roles [rid=2, rname=孙子]]]
		Roles [rid=3, rname=儿子]
		Roles [rid=1, rname=老公]
		Roles [rid=2, rname=孙子]

今天的测试就到这里了,希望大家看完以后自己测试一下

如果大家想浏览我的下一篇文章,请留言

此文章属于原创,不准随意转载:https://blog.csdn.net/LYQ2332826438

你可能感兴趣的:(java,Hibernate,代码示例,框架)