hibernate双向多对多关联映射XML与注解版

栏目: Hibernate · 发布时间: 7年前

内容简介:hibernate双向多对多关联映射XML与注解版

双向多对多关联映射原理:

假设,一个员工可能有多个角色,一个角色可能有多个员工,从员工或角色的角度看,这就是多对多的关系,不管从哪一个角度看,都是多对多的联系。多对多关联映射关系一般采用中间表的形式来实现,即新增一种包含关联双方主键的表。实现多对多关联关系,在数据库底层通过添加中间表指定关联关系,而在HIbernate框架在双方的实体中添加一个保存对方的集合,在双方的映射文件中使用<set>元素和<many-to-many>元素进行关联关系的配置。

如下图所示:

hibernate双向多对多关联映射XML与注解版

(1)XML版

Role类:

package Hibernate_demo1.Demo15.Entity;

import java.util.Set;

public class Role {
	
	private String id;
	private String rame;
	private Set<User> users;
	
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getRame() {
		return rame;
	}
	public void setRame(String rame) {
		this.rame = rame;
	}
	public Set<User> getUsers() {
		return users;
	}
	public void setUsers(Set<User> users) {
		this.users = users;
	}
}


package Hibernate_demo1.Demo15.Entity;

import java.util.Set;

public class User {

	private String id;
	private String uname;
	private Set<Role> roles;

	

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public Set<Role> getRoles() {
		return roles;
	}
	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	
	
}

Role.hbm.xml映射类:

<?xml version="1.0"?>  
<!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <class name="Hibernate_demo1.Demo15.Entity.Role" table="role">  
        <id name="id" type="java.lang.String"> 
            <column name="id"/>
            <generator class="uuid">  
            </generator>  
        </id>  
        <property name="rame" column="rname"/>
        
        <set name="users" table="user_role">  
            <key column="roleid"></key>  
            <many-to-many class="Hibernate_demo1.Demo15.Entity.User" column="userid"></many-to-many>  
        </set>  
    </class>  
</hibernate-mapping>

User.hbm.xml映射类:

<?xml version="1.0"?>  
<!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <class name="Hibernate_demo1.Demo15.Entity.User" table="user">  
        <id name="id">  
            <generator class="uuid">  
            </generator>  
        </id>  
        
        <property name="uname" column="uname"/>  
         
         <set name="roles" table="user_role">
			<key column="userid"/>
			<many-to-many class="Hibernate_demo1.Demo15.Entity.Role" column="roleid" />	
		</set>
    </class>  
</hibernate-mapping>

测试类:

package Hibernate_demo1.Demo15;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;

import Hibernate_demo1.Demo15.Entity.Role;
import Hibernate_demo1.Demo15.Entity.User;
import Hibernate_demo1.Demo15.Util.HibernateUtils;



public class App 
{
    public static void main( String[] args )
    {
        
    	Session session = null;
    	try{  
    		  
    	    session = HibernateUtils.getSession();
    	    session.beginTransaction();  
    	    

    	    Role r1 = new Role();
			r1.setRame("数据录入人员");
			session.save(r1);
			
			Role r2 = new Role();
			r2.setRame("商务主管");
			session.save(r2);
			
			Role r3 = new Role();
			r3.setRame("商务经理");
			session.save(r3);
			
			Role r4 = new Role();
			r4.setRame("项目会计");
			session.save(r4);
			
			User u1 = new User();
			u1.setUname("张三");
			Set<Role> u1Roles = new HashSet<Role>();
			u1Roles.add(r1);
			u1Roles.add(r2);
			u1.setRoles(u1Roles);
			session.save(u1);
			
			User u2 = new User();
			u2.setUname("李四");
			Set<Role> u2Roles = new HashSet<Role>();
			u2Roles.add(r1);
			u2Roles.add(r2);
			u2Roles.add(r3);
			u2.setRoles(u2Roles);
			session.save(u2);
			
			User u3 = new User();
			u3.setUname("王五");
			Set<Role> u3Roles = new HashSet<Role>();
			u3Roles.add(r3);
			u3Roles.add(r4);
			u3.setRoles(u3Roles);
			session.save(u3);
			
    	   
    	    session.getTransaction().commit();  
    	}catch(Exception e){  
    	    e.printStackTrace();  
    	    session.getTransaction().rollback();  
    	}finally{  
    	    HibernateUtils.closeSession(session);  
    	}
    }
}

执行结果:

Hibernate: 
    insert 
    into
        role
        (rname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role
        (rname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role
        (rname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role
        (rname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user
        (uname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user
        (uname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user
        (uname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)

数据库内容为:

user表:

hibernate双向多对多关联映射XML与注解版

role表:

hibernate双向多对多关联映射XML与注解版

user_role表:

hibernate双向多对多关联映射XML与注解版

示例: http://download.csdn.net/detail/u011781521/9835781

(2)注解版

Role类:

package Hibernate_demo1.Demo16.Entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="role")
public class Role {
	
	@Id
        @GenericGenerator(name="uuidGenerator", strategy="uuid")
        @GeneratedValue(generator="uuidGenerator")
	private String id;
	
	@Column(name="rname")
	private String rame;
	
	@ManyToMany(cascade=CascadeType.REFRESH,mappedBy="roles")
	private Set<User> users=new HashSet<User>();
	
	
	
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getRame() {
		return rame;
	}
	public void setRame(String rame) {
		this.rame = rame;
	}
	public Set<User> getUsers() {
		return users;
	}
	public void setUsers(Set<User> users) {
		this.users = users;
	}
}

User类:

package Hibernate_demo1.Demo16.Entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="user")
public class User {

	@Id
        @GenericGenerator(name="uuidGenerator", strategy="uuid")
        @GeneratedValue(generator="uuidGenerator")
	private String id;
	
	@Column(name="uname")
	private String uname;
	
	/*
	 * @ManyToMany表示多对多关联,对于这种关联极少数情况会使用级联删除,我这里设置的是级联刷新;
	 * 因为有中间表的存在这里使用@JoinTable来设置关联表后面的name配置的是关联表的名称
	 * inverseJoinColumn配置的是关系被维护一方主键对应的中间表字段
	 * joinColumn配置的是关系维护方主键对应的中间表字段。
	 */
	@ManyToMany(cascade=CascadeType.REFRESH)
	@JoinTable(name="user_role",inverseJoinColumns=@JoinColumn(name="roleid"),joinColumns=@JoinColumn(name="userid"))
	private Set<Role> roles=new HashSet<Role>();

	

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public Set<Role> getRoles() {
		return roles;
	}
	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	
	
}

测试类:

package Hibernate_demo1.Demo16;

import java.util.HashSet;
import java.util.Set;

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

import Hibernate_demo1.Demo16.Entity.Role;
import Hibernate_demo1.Demo16.Entity.User;


public class Test {

	public static void main(String[] args) {
		

    	SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
    	Session session = sessionFactory.getCurrentSession();  
    	Transaction tx = session.beginTransaction();  
        
   
    	//创建两个用户
        User us1=new User();
        us1.setUname("小明");
        
        User us2=new User();
        us2.setUname("小黑");
    	
        //创建用户集合
        Set<User> su=new HashSet<User>();
        su.add(us1);
        su.add(us2);
        
        
        //创建两个角色
        Role ro1=new Role();
        ro1.setRame("程序员");
        ro1.setUsers(su);
        
        Role ro2=new Role();
        ro2.setRame("技术经理");
        ro2.setUsers(su);
        
        
        //创建角色集合
        Set<Role> sr=new HashSet<Role>();
        sr.add(ro1);
        sr.add(ro2);
        
        //往用户添加角色集合
        us1.setRoles(sr);
        us2.setRoles(sr);
        
        //保存用户和角色
        session.save(us1);
        session.save(us2);
        session.save(ro1);
        session.save(ro2);
        
    	
        tx.commit();
        session.close();
	}

}

执行结果如下:

Hibernate: 
    insert 
    into
        user
        (uname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user
        (uname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role
        (rname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        role
        (rname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        user_role
        (userid, roleid) 
    values
        (?, ?)

示例: http://download.csdn.net/detail/u011781521/9835795


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

暗网

暗网

杰米·巴特利特 / 刘丹丹 / 北京时代华文书局 / 2018-7 / 59.00

全面深入揭秘“黑暗版淘宝”暗网的幕后世界和操纵者 现实中所有的罪恶,在暗网中,都是明码标价的商品。 暗杀、色情、恋童癖、比特币犯罪、毒品交易…… TED演讲、谷歌特邀专家、英国智库网络专家杰米•巴特利特代表作! 1、 被大家戏称为“黑暗版淘宝”的暗网究竟是什么?微信猎奇 文不能告诉你的真相都在这里了! 2、 因章莹颖一案、Facebook信息泄露危机而被国人所知的暗网......一起来看看 《暗网》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器