zoukankan      html  css  js  c++  java
  • 菜鸟学习Hibernate——多对多关系映射

       Hibernate中的关系映射,最常见的关系映射之一就是多对多关系映射例如用户与角色的关系,一个用户对应多个角色,一个角色对应多个用户。如图:


       Hibernate中如何来映射这两个的关系呢?

          下面就为大家讲解一下:

    1、创建实体类User和实体类Role

    User.java

    package com.bjpowernode.hibernate;
    
    import java.util.Set;
    
    public class User {
    	
    	private int id;
    	
    	private String name;
    
    	private Set roles;
    	
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public Set getRoles() {
    		return roles;
    	}
    
    	public void setRoles(Set roles) {
    		this.roles = roles;
    	}
    }
    


    Role.java


    package com.bjpowernode.hibernate;
    
    public class Role {
    
    	private int id;
    	
    	private String name;
    	
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    

    2、创建映射文件User.hbm.xml和Role.hbm.xml

    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="com.bjpowernode.hibernate.User" table="t_user">
    		<id name="id">
    			<generator class="native"/>
    		</id>
    		<property name="name"/>
    		<set name="roles" table="t_user_role">
    			<key column="user_id"/>
    			<many-to-many class="com.bjpowernode.hibernate.Role" column="role_id" />	
    		</set>
    	</class>
    </hibernate-mapping>


    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="com.bjpowernode.hibernate.Role" table="t_role">
    		<id name="id">
    			<generator class="native"/>
    		</id>
    		<property name="name"/>
    	</class>
    </hibernate-mapping>

    3、效果图



    Meet so Meet. C plusplus I-PLUS....
  • 相关阅读:
    C# 执行bat文件 PHP
    windows服务操作 sc批处理 PHP
    HTML 彩虹 PHP
    C# 简易日志记录类 PHP
    C# 读写INI文件 PHP
    .NET Framework PHP
    序列号备忘 PHP
    获取浏览器版本信息
    数据库中Image字段存储读取数据
    [转]装机推荐 5000元铸造最强游戏平台
  • 原文地址:https://www.cnblogs.com/iplus/p/4490383.html
Copyright © 2011-2022 走看看