• 菜鸟学习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....
  • 相关阅读:
    微信小程序-rpx
    vue项目页面切换到默认显示顶部
    访问formData的数据
    vue图片懒加载
    react+umi+dva
    switch判断中,case后面跟逻辑表达式出错
    给2020做一个小结
    react+next.js遇到的问题及解决
    域名相关(结构与规范)
    react+antd一边踩坑一边积累
  • 原文地址:https://www.cnblogs.com/iplus/p/4490383.html
Copyright © 2020-2023  润新知