Home Java javaTutorial hibernate_association mapping_one-to-many

hibernate_association mapping_one-to-many

Jun 23, 2017 pm 04:28 PM
hibernate one to many association mapping

hibernate mapping relationship

One-to-many, many-to-one,One-to-one, Many-to-many.

The commonly used ones are one-to-many and many-to-one.

In the database, you can express a one-to-many relationship by adding primary and foreign key associations; In hibernate, one party can hold multiple parties Set implementation, that is, using the element in the "one" end to represent the object holding the "many" end.

The following implements a "one-to-many" demo of addition, deletion, modification and search: one class corresponds to multiple students.

First create the student class Student

##
 1 package com.imooc.entity; 2  3 import java.io.Serializable; 4  5 public class Student implements Serializable { 6  7     private int sid; 8     private String sname; 9     private String sex;10     // 在多方定义一个一方的引用11     private Grade grade;12     13     public int getSid() {14         return sid;15     }16     public void setSid(int sid) {17         this.sid = sid;18     }19     public String getSname() {20         return sname;21     }22     public void setSname(String sname) {23         this.sname = sname;24     }25     public String getSex() {26         return sex;27     }28     public void setSex(String sex) {29         this.sex = sex;30     }31     public Grade getGrade() {32         return grade;33     }34     public void setGrade(Grade grade) {35         this.grade = grade;36     }37     38     public Student() {39         super();40     }41     42     public Student(String sname, String sex) {43         super();44         this.sname = sname;45         this.sex = sex;46     }47     48 }
Copy after login
View Code

Create class Grade

 1 package com.imooc.entity; 2  3 import java.io.Serializable; 4 import java.util.HashSet; 5 import java.util.Set; 6  7  8 public class Grade implements Serializable { 9 10     private int gid;11     private String gname;12     private String gdesc;13     private Set<Student> students = new HashSet<Student>();14     15     public int getGid() {16         return gid;17     }18     public void setGid(int gid) {19         this.gid = gid;20     }21     public String getGname() {22         return gname;23     }24     public void setGname(String gname) {25         this.gname = gname;26     }27     public String getGdesc() {28         return gdesc;29     }30     public void setGdesc(String gdesc) {31         this.gdesc = gdesc;32     }33     public Set<Student> getStudents() {34         return students;35     }36     public void setStudents(Set<Student> students) {37         this.students = students;38     }39     40     public Grade() {41         super();42     }43     44     public Grade(int gid, String gname, String gdesc) {45         super();46         this.gid = gid;47         this.gname = gname;48         this.gdesc = gdesc;49     }50     51     public Grade(String gname, String gdesc) {52         super();53         this.gname = gname;54         this.gdesc = gdesc;55     }56 }
Copy after login
View Code

Create the mapping file Student.hbm.xml of the Student class

 1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <!-- Generated 2017-6-1 14:49:09 by Hibernate Tools 3.5.0.Final --> 5 <hibernate-mapping> 6     <class name="com.imooc.entity.Student" table="STUDENT"> 7         <id name="sid" type="int"> 8             <column name="SID" /> 9             <generator class="increment" />10         </id>11         <property name="sname" type="java.lang.String">12             <column name="SNAME" />13         </property>14         <property name="sex" type="java.lang.String">15             <column name="SEX" />16         </property>17     </class>18 </hibernate-mapping>
Copy after login
View Code

Create the mapping file Grade.hbm.xml of the Grade class

 1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <!-- Generated 2017-6-1 14:49:09 by Hibernate Tools 3.5.0.Final --> 5 <hibernate-mapping> 6     <class name="com.imooc.entity.Grade" table="GRADE"> 7         <id name="gid" type="int"> 8             <column name="GID" /> 9             <generator class="increment" />10         </id>11         <property name="gname" type="java.lang.String">12             <column name="GNAME" length="20" not-null="true" />13         </property>14         <property name="gdesc" type="java.lang.String">15             <column name="GDESC" />16         </property>17         <!-- 指定关联的外键列 -->18         <set name="students" table="STUDENT">19             <key>20                 <column name="GID" />21             </key>22             <one-to-many class="com.imooc.entity.Student" />23         </set>24     </class>25 </hibernate-mapping>
Copy after login
View Code

Create hibernate configuration file

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6     <session-factory> 7         <property name="connection.username">root</property> 8         <property name="connection.password">root</property> 9         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>10         <property name="connection.url">11             <![CDATA[12                 jdbc:mysql://localhost:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF-813             ]]>14         </property>15         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>16         <property name="show_sql">true</property>17         <property name="format_sql">true</property>18         <property name="hbm2ddl.auto">update</property>19         20         <!-- 指定映射文件的路径 -->21         <mapping resource="com/imooc/entity/Grade.hbm.xml" />22         <mapping resource="com/imooc/entity/Student.hbm.xml" />23     </session-factory>24 </hibernate-configuration>
Copy after login
View Code

Write a test file for addition, deletion, modification and query

##
 1 package com.imooc.test; 2  3 import java.util.Set; 4  5 import org.hibernate.Session; 6 import org.hibernate.Transaction; 7  8 import com.imooc.entity.Grade; 9 import com.imooc.entity.Student;10 import com.imooc.util.HibernateUtil;11 12 /*13  * 单向一对多关系关系(班级--->学生)14  * 建立关联关系后,可以方便的从一个对象导航到另一个对象15  * 注意关联的方向16  */17 public class Test01 {18 19     public static void main(String[] args) {20         //add();21         //findStudentsByGrade();22         //update();23         delete();24     }25     26     //将学生添加到班级27     public static void add() {28         Grade g = new Grade("Java一班", "Java软件开发一班");29         Student s1 = new Student("杨康", "男");30         Student s2 = new Student("穆念慈", "女");31         32         //如果希望在学生表中添加对应的班级编号,需要在班级中添加学生,建立关联关系33         g.getStudents().add(s1);34         g.getStudents().add(s2);35         36         Session session = HibernateUtil.getSession();37         Transaction tr = session.beginTransaction();38         session.save(g);39         session.save(s1);40         session.save(s2);41         tr.commit();42         HibernateUtil.closeSession(session);43     }44     45     //查询班级中包含的学生46     public static void findStudentsByGrade() {47         Session session = HibernateUtil.getSession();48         Grade grade = (Grade) session.get(Grade.class, 1);49         System.out.println( grade.getGname() + "," + grade.getGdesc() );50         51         Set<Student> students = grade.getStudents();52         for(Student s : students) {53             System.out.println( s.getSname() + "," + s.getSex() );54         }55     }56     57     //修改学生信息58     public static void update() {59         Grade g=new Grade("Java二班", "Java软件开发二班");60         Session session = HibernateUtil.getSession();61         Transaction tr = session.beginTransaction();62         Student s = (Student) session.get(Student.class, 1);63         g.getStudents().add(s);64         session.save(g);65         tr.commit();66         HibernateUtil.closeSession(session);67     }68     69     //删除学生信息70     public static void delete() {71         Session session = HibernateUtil.getSession();72         Transaction tr = session.beginTransaction();73         Student s = (Student) session.get(Student.class, 2);74         session.delete(s);75         tr.commit();76         HibernateUtil.closeSession(session);77     }78 }
Copy after login
View Code

The above is the detailed content of hibernate_association mapping_one-to-many. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of MyBatis one-to-many query configuration: solving common related query problems Detailed explanation of MyBatis one-to-many query configuration: solving common related query problems Feb 22, 2024 pm 02:18 PM

Detailed explanation of MyBatis one-to-many query configuration: To solve common associated query problems, specific code examples are required. In actual development work, we often encounter situations where we need to query a master entity object and its associated multiple slave entity objects. In MyBatis, one-to-many query is a common database association query. With correct configuration, the query, display and operation of associated objects can be easily realized. This article will introduce the configuration method of one-to-many query in MyBatis, and how to solve some common related query problems. It will also

How to integrate Hibernate in SpringBoot project How to integrate Hibernate in SpringBoot project May 18, 2023 am 09:49 AM

Integrating Hibernate in SpringBoot Project Preface Hibernate is a popular ORM (Object Relational Mapping) framework that can map Java objects to database tables to facilitate persistence operations. In the SpringBoot project, integrating Hibernate can help us perform database operations more easily. This article will introduce how to integrate Hibernate in the SpringBoot project and provide corresponding examples. 1.Introduce dependenciesIntroduce the following dependencies in the pom.xml file: org.springframework.bootspring-boot-starter-data-jpam

Selected Java JPA interview questions: Test your mastery of the persistence framework Selected Java JPA interview questions: Test your mastery of the persistence framework Feb 19, 2024 pm 09:12 PM

What is JPA? How is it different from JDBC? JPA (JavaPersistence API) is a standard interface for object-relational mapping (ORM), which allows Java developers to use familiar Java objects to operate databases without writing SQL queries directly against the database. JDBC (JavaDatabaseConnectivity) is Java's standard API for connecting to databases. It requires developers to use SQL statements to operate the database. JPA encapsulates JDBC, provides a more convenient and higher-level API for object-relational mapping, and simplifies data access operations. In JPA, what is an entity? entity

Java Errors: Hibernate Errors, How to Handle and Avoid Java Errors: Hibernate Errors, How to Handle and Avoid Jun 25, 2023 am 09:09 AM

Java is an object-oriented programming language that is widely used in the field of software development. Hibernate is a popular Java persistence framework that provides a simple and efficient way to manage the persistence of Java objects. However, Hibernate errors are often encountered during the development process, and these errors may cause the program to terminate abnormally or become unstable. How to handle and avoid Hibernate errors has become a skill that Java developers must master. This article will introduce some common Hib

How to automatically associate MySQL foreign keys and primary keys? How to automatically associate MySQL foreign keys and primary keys? Mar 15, 2024 pm 12:54 PM

How to automatically associate MySQL foreign keys and primary keys? In the MySQL database, foreign keys and primary keys are very important concepts. They can help us establish relationships between different tables and ensure the integrity and consistency of the data. In actual application processes, it is often necessary to automatically associate foreign keys to the corresponding primary keys to avoid data inconsistencies. The following will introduce how to implement this function through specific code examples. First, we need to create two tables, one as the master table and the other as the slave table. Create in main table

What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate May 27, 2023 pm 05:06 PM

Hibernate's one-to-many and many-to-many Hibernate is an excellent ORM framework that simplifies data access between Java applications and relational databases. In Hibernate, we can use one-to-many and many-to-many relationships to handle complex data models. Hibernate's one-to-many In Hibernate, a one-to-many relationship means that one entity class corresponds to multiple other entity classes. For example, an order can correspond to multiple order items (OrderItem), and a user (User) can correspond to multiple orders (Order). To implement a one-to-many relationship in Hibernate, you need to define a collection attribute in the entity class to store

What are the differences between hibernate and mybatis What are the differences between hibernate and mybatis Jan 03, 2024 pm 03:35 PM

The differences between hibernate and mybatis: 1. Implementation method; 2. Performance; 3. Comparison of object management; 4. Caching mechanism. Detailed introduction: 1. Implementation method, Hibernate is a complete object/relational mapping solution that maps objects to database tables, while MyBatis requires developers to manually write SQL statements and ResultMap; 2. Performance, Hibernate is possible in terms of development speed Faster than MyBatis because Hibernate simplifies the DAO layer and so on.

In C language, what are Evaluation, Precedence and Association? In C language, what are Evaluation, Precedence and Association? Sep 03, 2023 pm 09:49 PM

The "C" compiler evaluates expressions according to precedence and associativity rules. If an expression contains operators of different precedence, precedence rules are taken into account. Here, 10*2 is evaluated first because '*' has higher precedence than '-' and '='. If the expressions contain the same precedence, the associativity rule is considered, i.e. from left to right (or from right to the left).

See all articles