Hibernate many-to-many mapping relationship

The many-to-many relationship mapping can be explained using the relationship between students and courses as an example. Usually, in order to facilitate data maintenance, many-to-many relationships will generate an intermediate table. The relationship between the student table and the curriculum table is shown in Figure 1.

Student table and curriculum table relationship


Figure 1 Relationship between student table and curriculum table


In Figure 1, the meanings of the fields in each table are as follows:

  • The students table is a student table, id is the primary key of the student table, and sname represents the name of the student.
  • The course table is the curriculum, id is the primary key of the curriculum, and cname represents the name of the course.
  • The s_c table is an intermediate table, and cid and sid represent foreign keys.


Since a student can study multiple courses, and a course can also be studied by multiple students, it can be seen that the relationship between students and courses is a many-to-many relationship. This relationship needs to introduce the objects of each other in the form of sets in the student class and the course class, and map them through the <set> tag in the mapping file.

In order for readers to better grasp the many-to-many relationship mapping, the following uses a specific case to demonstrate the use of the many-to-many relationship between students and courses. Specific steps are as follows.

1. Create an entity class

1) Create a student entity class.

Create a package named com.mengma.manytomany under the src directory, and create a Students class under the package, as shown below after editing.

package com.mengma.manytomany;

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

public class Students {
    private Integer id; // student id
    private String sname; // student name

    // A course can be studied by multiple students
    private Set<Course> courses = new HashSet<Course>();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Set<Course> getCourses() {
        return courses;
    }

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
}

In the above code, courses is a collection type, which is used to indicate that a student can study multiple courses.

2) Create a course entity class.

Create a class called Course under the com.mengma.manytomany package, and edit it as shown below.

package com.mengma.manytomany;

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

public class Course {
    private Integer id; // course id
    private String cname; // course name

    // A student can study multiple courses
    private Set<Students> students = new HashSet<Students>();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public Set<Students> getStudents() {
        return students;
    }

    public void setStudents(Set<Students> students) {
        this.students = students;
    }

}

In the above code, students is a collection type used to indicate that a course can be studied by multiple students.

2. Create a mapping file

1) Create a student entity class mapping file.

Create a mapping file named Students.hbm.xml under the com.mengma.manytomany package and edit it as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<!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.mengma.onetomany.Students" table="students">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <property name="sname" column="sname" length="40" />
        <set name="courses" table="s_c">
            <key column="sid" />
            <many-to-many class="com.mengma.manytomany.Course"
                column="cid" />
        </set>
    </class>
</hibernate-mapping>

In the above code, the <set> tag is used to describe the Set collection object in the mapped class. The difference from the one-to-many configuration method is that there is an additional table attribute in the <set> tag, which indicates the name of the intermediate table.

In the <set> tag, the column attribute of the <key> tag is used to describe the foreign key name of the students table in the intermediate table, and the <many-to-many> tag is used to represent the many-to-many relationship between two persistent classes , where the column attribute is used to describe the foreign key name of the course table in the intermediate table.

2) Create a course entity class mapping file.

Create a mapping file named Course.hbm.xml under the com.mengma.manytomany package as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<!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.mengma.onetomany.Course" table="sourse">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <property name="cname" column="cname" length="40" />
        <set name="students" table="s_c">
            <key column="cid" />
            <many-to-many class="com.mengma.manytomany.Students"
                column="sid" />
        </set>
    </class>
</hibernate-mapping>

It can be seen from the above code that the configuration and properties of Course.hbm.xml and Students.hbm.xml have the same meanings, which can be understood by reference.

3. Add mapping information

Add the Students.hbm.xml and Course.hbm.xml mapping file information in the hibernate.cfg.xml configuration file, as follows:

<mapping resource="com/mengma/manytomany/Students.hbm.xml" />
<mapping resource="com/mengma/manytomany/Course.hbm.xml" />

4. Create a test class

Create a class called ManyToManyTest under the com.mengma.manytomany package and edit it as shown below.

package com.mengma.manytomany;

import org.hibernate.classic.Session;
import org.junit.Test;

import com.mengma.utils.HibernateUtils;

public class ManyToManyTest {
    // adding data
    @Test
    public void test1() {
        Session session = HibernateUtils.getSession();
        session.beginTransaction();
        // create two students
        Students s1 = new Students();
        s1.setSname("Zhang San");
        Students s2 = new Students();
        s2.setSname("Lisi");
        // Create two subjects
        Course c1 = new Course();
        c1.setCname(" Java Basics");
        Course c2 = new Course();
        c2.setCname(" MySQL Basics");
        // Student related subjects
        s1.getCourses().add(c1);
        s2.getCourses().add(c1);

        s1.getCourses().add(c2);
        s2.getCourses().add(c2);
        // store
        session.save(c1);
        session.save(c2);
        session.save(s1);
        session.save(s2);
        session.getTransaction().commit();
        session.close();
    }

}

In the above code, first create two student objects and two course objects, and then use students to associate courses, which is a many-to-many one-way association. The many-to-many two-way association tutorial will be explained later in combination with the knowledge of inversion, so I won't go into details here.

5. Run the program and view the results

Use JUnit to test and run the test1() method. After running successfully, query the students table, course table and s_c table respectively. The query results are shown in Figure 2.
 

search result


Figure 2 query results


It can be seen from the query results in Figure 2 that the primary keys of the students table and the course table are respectively used as the foreign keys of the intermediate table. Since two students are studying two courses respectively, it can be seen that there are four records in the s_c table.

Guess you like

Origin blog.csdn.net/unbelievevc/article/details/132138834