Hibernate Getting Started Tutorial

Source: Internet
Author: User

In the previous article we will be a lot of one or one-to-many single-bilateral configuration, this article we mainly talk about a multi-to-many single-bilateral configuration

Hibernate Introductory Tutorial Fourth chapter

Hibernate multi-to-many configuration

Hibernate many-to-many is divided into 2 cases, that is, the third table (the intermediate table), if there is no other data in the intermediate table is one, if there is another data in the third table is one. We will explain each of the 2 cases below, and we choose the simplest course for students as an example.

no other fields in the middle table

1. Configuration files

Student class

public class Student200  implements Java.io.Serializable {    //fields         private Integer ID;     private String name;     Private set<course200> courses = new hashset<course200> ();    Constructors    /** Default constructor *    /Public Student200 () {    }        /** Full constructor *    /Public Student200 (String name, Set courses) {        this.name = name;        this.courses = courses;    }       Property accessors public    Integer getId () {        return this.id;    }        public void SetId (Integer id) {        this.id = ID;    }    Public String GetName () {        return this.name;    }        public void SetName (String name) {        this.name = name;    } Public set<course200> getcourses () {return courses;} public void setcourses (set<course200> courses) {this.courses = courses;}}

Student-Class configuration file Student200.hbm.xml

<?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 "><!--mapping file autogenerated by MyEclipse persistence Tools-->

Class classes

public class Course200  implements Java.io.Serializable {    //fields         private Integer ID;     private String name;     Private set<student200> students = new hashset<student200> ();    Constructors    /** Default constructor *    /Public Course200 () {    }        /** Full constructor *    /Public Course200 (String name) {        this.name = name;    }       Property accessors public    Integer getId () {        return this.id;    }        public void SetId (Integer id) {        this.id = ID;    }    Public String GetName () {        return this.name;    }        public void SetName (String name) {        this.name = name;    } Public set<student200> getstudents () {return students;} public void Setstudents (set<student200> students) {this.students = students;}}

<?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 "><!--mapping file autogenerated by MyEclipse persistence Tools-->

We can see how many many-to-many are used in the configuration file

2. Database operation
1. Inserting data

Insert data public static void Fun1 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans = Session.begintransaction (); Student200 stu = new Student200 (); Stu.setname ("Tomcat"); Course200 C1 = new Course200 () C1.setname ("C + +"); Stu.getcourses (). Add (C1); Course200 C2 = new Course200 () c2.setname ("Java"); Stu.getcourses (). Add (C2); Session.save (Stu); Session.save (C1); Session.save (C2); Trans.commit (); Session.close ();}

2. Query data

Query data public static void Fun2 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Query query = Session.createquery ("Select S,s.name,c.name from Student200 s left join fetch s.courses C"); list<object[]> list = Query.list (); for (object[] o:list) {System.out.println (o[1]+ "" +o[2]);}}

We're looking at some of the data here, and we're using fetch, and we've got lazy usage in the last few, and we know that hibernate defaults to lazy as true, so we have to pull the information from the students to fetch the course. I want to explain that the select S,s.name,c.name from Student200 s left join fetch s.courses C statement do not fetch effect is the same, left join and left join FETCH The effect here is the same, do not know why hibernate can be used in these 2 kinds of usage.

3. Update data

More rows data public static void Fun3 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans = Session.begintransaction (); Course200 C = (Course200) session.get (Course200.class, 1); C.setname ("PHP"); Session.save (c); Trans.commit (); Session.close ();}

4. Delete data

Delete data public static void Fun4 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans = Session.begintransaction (); Course200 C = (Course200) session.get (Course200.class, 2); Session.delete (c); Trans.commit (); Session.close ();}
Twothere are other fields in the middle table

There are other fields in the middle table that are slightly different in hibernate, we also take the student class as an example, we want to add the score in the third table in this field, there are no extra fields, we have 2 classes, 2 configuration files, if there are other fields in the intermediate table, Then we have to produce the class and configuration file of the intermediate table, and in Hibernate, many-to-many will be split into 2 one-to-many cases (of course there are other configurations, we give a general configuration here).

Below we give the configuration method

1. Configuration files

Student class

Package Com.sunny.entity202;import Java.util.hashset;import java.util.set;/** * Student200 entity. @author MyEclipse Persistence Tools */public class Student200 implements java.io.Serializable {//Fields Priv     Ate Integer StudentID;     private String name;    Private Set SCs = new HashSet (0);//scs corresponds to the third table selected timetable//constructors/** default constructor */Public Student200 () {        }/** Full Constructor */public Student200 (String name, Set SCs) {this.name = name; This.    SCS = SCS;    }//Property accessors Public Integer Getstudentid () {return this.studentid;    } public void Setstudentid (Integer studentid) {this.studentid = StudentID;    } public String GetName () {return this.name;    } public void SetName (String name) {this.name = name; } public Set Getscs () {return this.    SCs; } public void Setscs (Set SCs) {this.    SCS = SCS; }}

Student configuration Files

<?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 "><!--mapping file autogenerated by MyEclipse persistence Tools-->

Course Category

public class Course200  implements Java.io.Serializable {    //fields         private Integer CourseID;     private String name;     Private Set SCs = new HashSet (0);    Constructors    /** Default constructor *    /Public Course200 () {    }        /** Full constructor *    /Public Course200 (String name, Set SCs) {        this.name = name;        This. SCS = SCS;    }       Property accessors public    Integer Getcourseid () {        return this.courseid;    }        public void Setcourseid (Integer courseid) {        This.courseid = CourseID;    }    Public String GetName () {        return this.name;    }        public void SetName (String name) {        this.name = name;    }    Public Set Getscs () {        return this. SCs;    }        public void Setscs (Set SCs) {this        . SCS = SCS;    }}

Course configuration file

<?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 "><!--mapping file autogenerated by MyEclipse persistence Tools-->

Intermediate table, select class of timetable

Package com.sunny.entity202;/** * SC entity. @author MyEclipse Persistence Tools */public class SC implements java.io.Serializable {//Fields private Inte     GER ID;     Private Student200 student200;     Private Course200 course200;    Private Integer score; Constructors/** Default constructor */Public SC () {}/** Minimal constructor * Public SC (Student200 Stud        ent200, Course200 course200) {this.student200 = student200;    this.course200 = course200; }/** Full Constructor */public SC (Student200 student200, Course200 course200, Integer score) {This.stu        dent200 = student200;        this.course200 = course200;    This.score = score;    }//Property accessors Public Integer getId () {return this.id;    } public void SetId (Integer id) {this.id = ID;    } public Student200 getStudent200 () {return this.student200;       } public void setStudent200 (Student200 student200) { this.student200 = student200;    } public Course200 getCourse200 () {return this.course200;    } public void setCourse200 (Course200 course200) {this.course200 = course200;    } public Integer Getscore () {return this.score;    } public void SetScore (Integer score) {This.score = score; }}

Class Selection Profile

<?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 "><!--mapping file autogenerated by MyEclipse persistence Tools-->


We can see from the above configuration that many-to-many were split into 2 one-to-many

2. Data manipulation

Here we give an added operation, the others are the same

Insert data public static void Fun1 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans  = Session.begintransaction (); Student200 stu = new Student200 (); Stu.setname ("Apache"); Course200 c  = new Course200 (); C.setname ("Java"); SC sc = new SC (); sc.setcourse200 (c); sc.setstudent200 (Stu); Sc.setscore (in); Session.save (Stu); Session.save (c); Session.save (SC); Trans.commit (); Session.close ();}


Summary: I've added a primary key ID in the case of many-to-many configurations with extra fields (a field with more scores), and in the first case I didn't add the ID (only 2 fields in the class schedule, student ID and course ID, Federated primary key), The second case I want to add an ID is because if I do not add an ID, then the student ID and the course ID is the federated primary key, then there will be a class to store the federated primary Key, look at the trouble, so I do.

In many-to-many configuration, like lazy, cascade, fetch, inverse in the front I have said, you can choose the configuration according to their own situation, as for the unilateral configuration, as long as the deletion of the class and configuration files in the relevant places can be, here no longer repeat








Hibernate Getting Started Tutorial

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.