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....
  • 相关阅读:
    SVN: repository browser 库浏览器
    创业泡沫真他妈的大出血来了 --个人需要创业以谋生,行业需要创业以求变,国家需要创业以维稳
    判断输入的是否是大于0的正整数
    linux开放或限制端口和ip访问
    linux模糊删除es索引脚本
    ssh免密登录
    DES加密解密
    SpringBoot 单元测试
    SpringContextHolder 工具类
    fiddler抓包 443 请求不到数据
  • 原文地址:https://www.cnblogs.com/iplus/p/4490383.html
Copyright © 2011-2022 走看看