Hibernate---One-to-many association mappings

Source: Internet
Author: User

Hibernate notes (ii) Mapping types
    1. One-to-many (one to many)
    2. Multi-pair (many to one)
    3. One-to-one (one to one)
    4. Many-to-many (many to many)
One-to-many associations

In the database, you can represent a one-to-many relationship by adding a primary foreign key association

Development jar Package under MyEclipse

1. Manually add the JAR package

    1. Create a Lib and copy the jar package to Lib
    2. Select all jar packages in the Lib directory
    3. right mouse button-bulid path

2.IDE support itself

right mouse button-myeclipse-add Hibernate capabilities

or project facets (capabilities)

Hibernate master configuration file

Extract package copy of Hibernate

Cfg.xml (shorthand for config)

<! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">
Creating a tool class
Package Util;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.boot.registry.standardserviceregistry;import Org.hibernate.boot.registry.standardserviceregistrybuilder;import Org.hibernate.cfg.configuration;public Class    Hibernateutil {private static sessionfactory sessionfactory;    private static session session;         static {//Creates a configuration object, reads the master profile Cfg.xml, finishes initializing configuration config = new configuration (). Configure (); The method used by Hibernate 4.x standardserviceregistrybuilder SSRB = new Standardserviceregistrybuilder (). Applysetti        NGS (Config.getproperties ());        Standardserviceregistry SSR = Ssrb.build ();    sessionfactory= config.buildsessionfactory (SSR);    }//Get sessionfactory public static Sessionfactory Getsessionfactory () {return sessionfactory;    }//Get session public static session getsession () {return sessionfactory.opensession (); }//closed session public static void CLOSesession (Session session) {if (session!=null) {session.close (); }    }}
    1. Gets the session's tool class
Creating tables in MySQL Database

Create a Students.sql file

create table grade(    gid int primary key,    gname varchar(20) not null,    gdesc varchar(50));create table student(    sid int primary key,    sname varchar(20) not null,    sex char(2),    gid int);//外键约束alter table student add constraint fk_student_gid foreign key (gid)references grade(gid);
Creating a persisted class

A one-to-many relationship, a class corresponding to multiple students

Student Class
Package entity;

import java.io.Serializable;public class Student implements Serializable {    private int sid;    private String sname;    private String sex;    public int getSid() {        return sid;    }    public void setSid(int sid) {        this.sid = sid;    }    public String getSname() {        return sname;    }    public void setSname(String sname) {        this.sname = sname;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }}

Class classes

Package Entity;import Java.io.serializable;import Java.util.hashset;import java.util.set;public class Grade    Implements Serializable {private int gid;    Private String Gname;    Private String Gdesc; /** 1. Define a collection of parties in a party 2. With set collection, students cannot repeat */private set<student> students = new HASHSET&LT;STUDENT&G    t; ();    public int Getgid () {return GID;    } public void SetGid (int gid) {this.gid = gid;    } public String Getgname () {return gname;    } public void Setgname (String gname) {this.gname = Gname;    } public String Getgdesc () {return gdesc;    } public void Setgdesc (String gdesc) {this.gdesc = Gdesc;    } public set<student> getstudents () {return students;    } public void Setstudents (set<student> students) {this.students = students; } public Grade () {} public Grade (int gid, string gname, String gdesc, set<student> students) {Supe     R ();   This.gid = GID;        This.gname = Gname;        This.gdesc = Gdesc;    This.students = students; }}
Configuration of the mapping file

Class Grade Mapping File

    1. Class mapping File
    2. The class tag corresponds to the persisted class, table in the table corresponding to the database
    3. The ID tag is the primary key and the generator corresponds to the build policy
    4. The property tag corresponds to another attribute

Student Student Mapping File

Test

One-to-many relationship (class-student)

Class construction method (Wihtout ID and students)
Student's construction method (without ID) and non-parametric construction method

Add the corresponding class number to the student table, you need to add students to the class, establish an association relationship

Package Entity;import Java.util.set;import Org.hibernate.session;import org.hibernate.transaction;import        Util.hibernateutil;public class Test {public static void main (string[] args) {//add ();        Findstudentbygrade ();        Update ();    Delete ();        }//Add students to class public static void Add () {Grade g = new Grade ("One Class electrical", "Information Academy");        Student stu1 = new Student ("Still", "female");        Student STU2 = new Student ("Pastoral Month", "female");        To add the corresponding class number to the student table, you need to add students to the class and establish an association relationship g.getstudents (). Add (STU1);        G.getstudents (). Add (STU2);        Session session = Hibernateutil.getsession ();        Transaction tx = Session.begintransaction ();        Session.save (g);        Session.save (STU1);        Session.save (STU2);        Tx.commit ();    Hibernateutil.closesession (session);     }//Student Information inquiry, Class middle School students ' information//establish association relationship, you can easily navigate from one object to another//note the direction of the Association class---> Student public static void Findstudentbygrade ()  {Session session = Hibernateutil.getsession ();      Grade Grade = (Grade) session.get (grade.class,1);        System.out.println (Grade.getgname () + "," +grade.getgdesc ());        set<student> students = grade.getstudents ();        for (Student stu:students) {System.out.println (Stu.getsname () + "," +stu.getsex ());        }}//modify student information public static void update () {Grade g = new Grade ("Hiking Class", "Hiking Academy");        Session session = Hibernateutil.getsession ();        Transaction tx = Session.begintransaction ();        Student stu = (Student) session.get (Student.class, 1);        G.getstudents (). Add (Stu);        Session.save (g);        Tx.commit ();    Hibernateutil.closesession (session);        }//Delete student information public static void Delete () {Session session = Hibernateutil.getsession ();        Transaction tx = Session.begintransaction ();        Student stu = (Student) session.get (Student.class, 1);        Session.delete (Stu);        Tx.commit ();    Hibernateutil.closesession (session); }}

One-way many-to-one association

By using a reference in the multi-party holder, you need to use the

    1. Define a multi-party reference in a multi-party persistence class, and generate Getter/setter
    2. Configuration of the mapping file (multi-party);

      Package test;

      Import org.hibernate.Session;
      Import org.hibernate.Transaction;

      Import Util.hibernateutil;
      Import entity. Grade;
      Import entity. Student;

      Test one-way many-to-one (student-Class)

      public class Test2 {
      public static void Main (string[] args) {
      Save ();
      }

      //保存public static void save(){    Grade g = new Grade("电气一班", "信息学院");    Student stu1 = new Student("王九九","女");    Student stu2 = new Student("林浣溪", "女");    //设置关联关系    stu1.setGrade(g);    stu2.setGrade(g);    Session session = new hibernateUtil().getSession();    Transaction tx = session.beginTransaction();    session.save(g);    session.save(stu1);    session.save(stu2);    tx.commit();    hibernateUtil.closeSession(session);}

      }

Bidirectional many-to-one
package test;import org.hibernate.Session;import org.hibernate.Transaction;import util.hibernateUtil;import entity.Grade;import entity.Student;//测试单向多对一(学生--->班级)public class Test2 {    public static void main(String[] args) {        save();    }    //保存    public static void save()    {        Grade g = new Grade("电气一班", "信息学院");        Student stu1 = new Student("王九九","女");        Student stu2 = new Student("林浣溪", "女");        //设置关联关系        g.getStudents().add(stu1);        g.getStudents().add(stu2);        stu1.setGrade(g);        stu2.setGrade(g);        Session session = new hibernateUtil().getSession();        Transaction tx = session.beginTransaction();        session.save(g);        session.save(stu1);        session.save(stu2);        tx.commit();        hibernateUtil.closeSession(session);    }}
Inverse property

Set Label
Specifies the control direction of the association relationship, which is maintained by one side by default
In an association relationship, the inverse= "false" is the active party, which is responsible for maintaining the association relationship
In a one-to-many association, only one side of inverse is set to true, which can help improve performance

Cascade Property
session.save(g);session.save(stu1);session.save(stu2);
    1. Operation Trouble, save class, still need to save student's operation
    2. Cascade Operation Simplification

Hibernate automatically persists the associated object when the Cascade property is not set to none

The setting of the Cascade property will result in performance changes and should be carefully set

Query operations

Find information about your student's class

//查询学生所在班级信息public static void findGradeByStudent(){    Session session = hibernateUtil.getSession();    Student stu =(Student) session.get(Student.class, 2);    System.out.println(stu.getSid()+","+stu.getSname()+","+stu.getSex());    Grade g = stu.getGrade();    System.out.println(g.getGid()+","+g.getGname()+","+g.getGdesc());    hibernateUtil.closeSession(session);}
Summarize

Implement one-to-many

    1. Add a collection that holds the many party in the entity of one side
    2. Add One-to-many tags to the one-side configuration file

Implement one-way many-to-one

    1. Add one-side references to entities in the many party
    2. Add Many-to-one tags to the many side's configuration file

Common Properties

    1. Cascade: Setting cascading relationships
    2. Inverse: Set which party maintains the affinity relationship
MyEclipse Tips for use

Use the support provided by the IDE to simplify operations

Add a database connection view

upper right corner of MyEclipse-open perspective-myeclipse Database Explorer

or a

Menu bar-window-show view-other expand myeclipse Database Select DB Browser

Reverse engineering

Automatic generation of persisted classes and mapping relationship files based on tables in the database

To create a physical package entity

Resources
    1. IMOOC Hibernate one of the multiple mappings
    2. Code

Hibernate---One-to-many association mappings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.