search
HomeJavajavaTutorialhibernate_association mapping_one-to-many

hibernate_association mapping_one-to-many

Jun 23, 2017 pm 04:28 PM
hibernateone to manyassociationmapping

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 }
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 }</student></student></student></student>
View Code

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

 1 <?xml  version="1.0"?> 2 nbsp;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> 7         <id> 8             <column></column> 9             <generator></generator>10         </id>11         <property>12             <column></column>13         </property>14         <property>15             <column></column>16         </property>17     </class>18 </hibernate-mapping>
View Code

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

 1 <?xml  version="1.0"?> 2 nbsp;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> 7         <id> 8             <column></column> 9             <generator></generator>10         </id>11         <property>12             <column></column>13         </property>14         <property>15             <column></column>16         </property>17         <!-- 指定关联的外键列 -->18         <set>19             <key>20                 <column></column>21             </key>22             <one-to-many></one-to-many>23         </set>24     </class>25 </hibernate-mapping>
View Code

Create hibernate configuration file

 1 <?xml  version="1.0" encoding="UTF-8"?> 2 nbsp;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>root</property> 8         <property>root</property> 9         <property>com.mysql.jdbc.Driver</property>10         <property>11             14         </property>15         <property>org.hibernate.dialect.MySQLDialect</property>16         <property>true</property>17         <property>true</property>18         <property>update</property>19         20         <!-- 指定映射文件的路径 -->21         <mapping></mapping>22         <mapping></mapping>23     </session-factory>24 </hibernate-configuration>
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 }</student>
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
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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.