search
HomeJavajavaTutorialjava Hibernate many-to-many mapping detailed explanation and example code

java Hibernate many-to-many mapping

Foreword:

1. One-way many-to-many

Examples of one-way many-to-many use people and positions For example, a person can have multiple positions, and a position can have multiple people. One-way many-to-many means that only one end can query and obtain the content of the other end. A many-to-many relationship will generate an association table before the object when generating the relationship model. The association table stores the primary keys of the two relationship tables. Their relationship is as follows:

java Hibernate多对多映射详解及实例代码

java Hibernate多对多映射详解及实例代码

Code part:

(1) Mapping and relationship class

Because it is a one-way relationship, it only needs to be maintained at one end, so we You need to add the tag to the User.hbm.xml configuration file, add the corresponding column relationship to the tag, and add the table attribute to the table to indicate the generation of a new table, User. The hbm.xml code is as follows:

<span style="font-family:KaiTi_GB2312;font-size:18px;"><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></span>

##Role.hbm.xml code is relatively simple and there is no need to add extra tags to maintain relationships:

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

Because there is set mapping in the user mapping, you need to add Hashset to the corresponding class file. The User.java code is as follows:

<span style="font-family:KaiTi_GB2312;font-size:18px;">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;
  }
}</span>

Role.java code is as follows:

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) Add and read data:

Add When data is generated, you need to first save the relationship to the database, then create the user Hash table, add the corresponding relationship to the hash table, and finally create the user and add the hash table to the user. What needs to be paid attention to in this part is the order of writing, otherwise there will be many null values, which is the same as the previous mapping.

public void testSave1() {
    Session session = null;
    try {
      session = HibernateUtils.getSession();
      session.beginTransaction();
        
      Role r1 = new Role();
      r1.setName("数据录入人员");
      session.save(r1);
        
      Role r2 = new Role();
      r2.setName("商务主管");
      session.save(r2);
        
      Role r3 = new Role();
      r3.setName("商务经理");
      session.save(r3);
        
      Role r4 = new Role();
      r4.setName("项目会计");
      session.save(r4);
        
      User u1 = new User();
      u1.setName("张三");
      Set u1Roles = new HashSet();
      u1Roles.add(r1);
      u1Roles.add(r2);
      u1.setRoles(u1Roles);
      session.save(u1);
        
      User u2 = new User();
      u2.setName("李四");
      Set u2Roles = new HashSet();
      u2Roles.add(r1);
      u2Roles.add(r2);
      u2Roles.add(r3);
      u2.setRoles(u2Roles);
      session.save(u2);
        
      User u3 = new User();
      u3.setName("王五");
      Set u3Roles = new HashSet();
      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);
    }
  }


When reading, because it is a one-way relationship, you only need to read the content of the other end through one, and read the role through user content. The code is as follows:

public void testLoad1() {
    Session session = null;
    try {
      session = HibernateUtils.getSession();
      session.beginTransaction();
      User user = (User)session.load(User.class, 2);
      System.out.println(user.getName());
      for (Iterator iter=user.getRoles().iterator(); iter.hasNext();) {
        Role role = (Role)iter.next();
        System.out.println(role.getName());
      }
      session.getTransaction().commit();
    }catch(Exception e) {
      e.printStackTrace();
      session.getTransaction().rollback();
    }finally {
      HibernateUtils.closeSession(session);
    }
  }

2. Two-way many-to-many mapping

As introduced before, two-way many-to-many maintains the relationship at both ends at the same time, from either end The content can be loaded to the other end. Without further ado, let’s get straight to the code:

Because it is bidirectional, it is necessary to add bidirectional collection mapping at the same time. Add the tag in the configuration file to add multiple pairs. For multiple tags, the Role.hbm.xml code is as follows:

<hibernate-mapping>
  <class name="com.bjpowernode.hibernate.Role" table="t_role">
    <id name="id">
      <generator class="native"/>
    </id>
    <property name="name"/>
    <set name="users" table="t_user_role">
      <key column="role_id" not-null="true"/>
      <many-to-many class="com.bjpowernode.hibernate.User" column="user_id"/>
    </set>
  </class>
</hibernate-mapping>

The User.hbm.xml code is as follows, which is the same as the one-way mapping code:

<hibernate-mapping>
  <class name="com.bjpowernode.hibernate.Role" table="t_role">
    <id name="id">
      <generator class="native"/>
    </id>
    <property name="name"/>
    <set name="users" table="t_user_role">
      <key column="role_id" not-null="true"/>
      <many-to-many class="com.bjpowernode.hibernate.User" column="user_id"/>
    </set>
  </class>
</hibernate-mapping>

Role.java part, like the one-way user.java, you need to add a collection mapping set. The code is as follows:

import java.util.Set;
  
public class Role {
  
  private int id;
    
  private String name;
    
  private Set users;
    
  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 getUsers() {
    return users;
  }
  
  public void setUsers(Set users) {
    this.users = users;
  }
}

User.hbm.xml The User.java code is the same as the code above, so I won’t put it all here.


Summary:

Through the introduction of several blogs, I believe everyone has understood one-way and multi-way. We only need to remember one-way and two-way. It is quite simple. of.


Thank you for reading, I hope it can help you, thank you for your support of this site!

For more java Hibernate many-to-many mapping details and example code related articles, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools