Hibernate Association Mappings

Source: Internet
Author: User

This article can be used as a learning note for the Beijing Academy Horse Soldier Hibernate course.
Hibernate mapping, mainly divided into one-to-many, a lot of a, many-to-many, but also one-way and two-way difference.
OK, don't dwell on the name, we begin to look at the example.


One-way husband is an entity, wife is also an entity.
A husband has only one wife, while a wife also has only one husband.
The relationship above is called a one-to-one.
What do you mean one way?
Look at the code:
Package com.bjsxt.hibernate; @Entitypublic class Husband {    private int id;    private String name;    Private Wife Wife;        @Id    @GeneratedValue Public    int getId () {        return Id;    }        @OneToOne    @JoinColumn (name= "Wifeid") public    Wife Getwife () {        return Wife;    }    Omit get set}package com.bjsxt.hibernate; @Entitypublic class Wife {    private int id;    private String name;        @Id    @GeneratedValue Public    int getId () {        return Id;    }    Omit get Set}


Look at the code above, the husband has a wife's reference, and wife inside there is no wife's reference.
In other words at the code level, according to the husband we can get his wife, but according to the wife can't get husband. (This is one way)

Let's look at the code it runs
Package Com.bjsxt.hibernate;import Org.hibernate.cfg.annotationconfiguration;import Org.hibernate.tool.hbm2ddl.schemaexport;public class Test {public    static void Main (string[] args) {        new Schemaexport (New Annotationconfiguration (). Configure ()). Create (false, True);}        }
In Hibernate's config file
Plus
<property name= "Hbm2ddl.auto" >update</property>
Results
19:41:04,229 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    CREATE TABLE Husband (        ID integer NOT NULL auto _increment,        name varchar (255),        Wifeid Integer,        primary key (ID)    ) 19:41:04,549 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    CREATE TABLE Wife (        ID integer NOT NULL auto_increment,        name varchar (255),        primary key (ID)    ) 19:41:04,880 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    ALTER TABLE Husband        add index fkaeea401b109e78ed (wifeid),        add constraint fkaeea401b109e78ed        Foreign Key (Wifeid)        references Wife (ID)

First add a field to husband, Wifeid, and then let him refer to the ID field of the wife table as a foreign key.
As you can see, @JoinColumn (name= "Wifeid") this meta tag indicates the name of the associated field within the husband table.
What if we don't have this meta tag?
Then the associated field is: wife_id. That is Tablename_primarykey.
If you write the @onetoone into wife (there is no onotoone tag in husband), then we can get husband from wife (at the code level).



One-to-one two-way if I want to get wife from husband, I also want to get husband from wife. What then?
Make a copy of the label in the husband and it's OK.
Package com.bjsxt.hibernate; @Entitypublic class Wife {    private int id;    private String name;    Private Husband Husband;        @Id    @GeneratedValue Public    int getId () {        return Id;    }        @OneToOne    @JoinColumn (name= "Husbandid") public    Husband Gethusband () {        return Husband;    }}

OK, the above code, wife can also be taken to husband.
Let's look at hibernate-generated SQL
CREATE TABLE Husband (        ID integer NOT NULL auto_increment,        name varchar (255),        Wifeid Integer,        Primary Key (ID)    ) 19:53:20,487 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    CREATE TABLE Wife (        ID integer Not NULL auto_increment,        name varchar (255),        husbandid Integer,        primary key (ID)    ) 19:53:20,824 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    ALTER TABLE Husband        add index fkaeea401b109e78ed (Wifeid),        add constraint fkaeea401b109e78ed        foreign key (Wifeid) references        Wife (ID) 19:53:21,421 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    ALTER TABLE Wife        add index fk292331ce01a6e1 (husbandid),        add constraint fk292331ce01a6e1        foreign key (husbandid)        references Husband (ID)
See, wife inside has the foreign key, husband inside also has the foreign key!
It's not redundant.
Change the wife class to look like this.
    @OneToOne (mappedby= "wife") public    Husband Gethusband () {        return Husband;    }
This mappedby means that I (wife) and husband this class are one-to-one, but the associated foreign key is controlled by the Getwife method of the husband class.
Run a bit.
20:03:18,611 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-create table Husband (ID integer NOT NULL auto _increment, name varchar (255), Wifeid Integer, primary key (ID)) 20:03:18,618 ERROR org.hibernate.  Tool.hbm2ddl.schemaexport:348-unsuccessful:create table Husband (ID integer NOT NULL auto_increment, name varchar (255), Wifeid Integer, primary key (ID)) 20:03:18,618 ERROR org.hibernate.tool.hbm2ddl.schemaexport:349-table ' husband ' alread  Y exists20:03:18,619 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-create table Wife (ID integer NOT NULL Auto_increment, name varchar (255), primary key (ID)) 20:03:18,933 DEBUG Org.hibernate.tool.hbm2ddl.Schem Aexport:377-alter Table Husband Add index fkaeea401b109e78ed (wifeid), add constraint fkaeea401b109e78e D foreign KEY (Wifeid) references Wife (ID)
In the database, there is no foreign key in the wife table.
However, at the code level we can still get husband from the wife class.

Note the above @OneToOne (mappedby= "wife")
Only a two-way association, it is best to write on Mappedby, two tables have a foreign key is enough.



Many-to-one one-way association everyone has a lot of dreams, but every dream belongs to a specific person.
Let's start with how the Java code is implemented in the database.
The two tables above, one is person, the inside is Id,name
Then Dream table, an ID, a description.
So which table are their foreign keys on?
In the dream, in other words, the Dream table has a field called PersonID.
The reason for this is not explained.
All A-to-many, many-to-one relationship, in the database, foreign keys are placed on the side of many.
Why. Think of yourself.


Look at the code
Package com.bjsxt.hibernate; @Entitypublic class Dream {    private int id;    Private String description;        private person person;        @Id    @GeneratedValue Public    int getId () {        return Id;    }    @ManyToOne    @JoinColumn (name= "personId") Public person    Getperson () {        return person;    }    Omit get set}package com.bjsxt.hibernate; @Entitypublic class Person {    private int id;    private String name;        @Id    @GeneratedValue Public    int getId () {        return Id;    }        Omit get Set}
See "Many-to-one-way" from the code level
Is that I can get one of the many (the dream) side (person).
Because it is one-way, he cannot get all his dream from the person.
OK, the generated table, dream in the PersonID.
20:20:21,970 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    CREATE TABLE Dream (        ID integer NOT NULL auto_ Increment,        description varchar (255),        personId Integer,        primary key (ID)    ) 20:20:22,264 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    CREATE TABLE person (        ID integer NOT NULL auto_increment,        Name varchar (255),        primary key (ID)    ) 20:20:22,765 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-    ALTER TABLE Dream        add index fk3f397e3c1409475 (personId),        add constraint fk3f397e3c1409475        foreign key ( PERSONID)        references person (ID)



One-to-many one-way associations are also examples of people and dreams.
I want to be at the level of code, through people to get all his dreams, how to do?
First delete the person's reference in the Dream class
Package Com.bjsxt.hibernate, @Entitypublic class Person {    private int id;    private String name;    Private set<dream> dreams=new hashset<> ();        @Id    @GeneratedValue Public    int getId () {        return Id;    }    @OneToMany    @JoinColumn (name= "Psrsonid") public    set<dream> Getdreams () {        return dreams;    }    }


OK, you are done.
The Build table statement is the same as above.
The set of Dream collection why is set?list Line no, map line not?
All right.
But remember, the records inside the database are unordered and unequal.
Which do you mean to use?


whether it's Onetomany or Manytomany, plus @JoinColumn (name= "abc")
is a foreign key called ABC, which is added to the smaller party.


One-to-many bidirectional association (many-to-two-way correlation) The following example, as you can guess, is that I want to get the person it belongs to from the dream, and I want to get all his dream.
Let's look at the code:
Package com.bjsxt.hibernate; @Entitypublic class Dream {    private int id;    Private String description;        private person person;        @Id    @GeneratedValue Public    int getId () {        return Id;    }    public void setId (int id) {        this.id = ID;    }    @ManyToOne    @JoinColumn (name= "personId") Public person    Getperson () {        return person;    }} Package Com.bjsxt.hibernate, @Entitypublic class Person {    private int id;    private String name;    Private set<dream> dreams=new hashset<> ();    @Id    @GeneratedValue Public    int getId () {        return Id;    }    @OneToMany (mappedby= "person") public    set<dream> Getdreams () {        return dreams;    }}
OK, we can get the person by the dream in the code, and we can get the dream by person.



Many-to-many one-way association examples are simple, a teacher can teach many students, a student can be taught by multiple teachers.
One-way is to say that either the teacher can "know" his students, or students can know their teachers.
We first see the teacher can "know" the code of their students.

Package com.bjsxt.hibernate; @Entitypublic class Student {    private int id;    private String name;        @Id    @GeneratedValue Public    int getId () {        return Id;}    } OK, there is no teacher's citation in the students. Package com.bjsxt.hibernate; @Entitypublic class Teacher {    private int id;    private String name;    Private set<student> students = new hashset<student> ();    @Id    @GeneratedValue Public    int getId () {        return Id;    }        @ManyToMany    @JoinTable (name= "t_s",        joincolumns={@JoinColumn (name= "teacher_id")},        inversejoincolumns={@JoinColumn (name= "student_id")}        ) public    set<student> getstudents () {        return students;}    }
Look at the results:
21:10:35,854 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-create table Student (ID integer NOT NULL auto _increment, name varchar (255), primary key (ID)) 21:10:36,192 DEBUG Org.hibernate.tool.hbm2ddl.SchemaExpo  Rt:377-create table Teacher (ID integer NOT NULL auto_increment, name varchar (255), primary key  (ID)) 21:10:36,643 DEBUG org.hibernate.tool.hbm2ddl.schemaexport:377-create table t_s (teacher_id integer Not NULL, student_id integer NOT NULL, primary key (teacher_id, student_id)) 21:10:36,947 DEBUG Org.hibe Rnate.tool.hbm2ddl.schemaexport:377-alter Table t_s Add index fk1bf68bf77ba8a (teacher_id), add Constra int fk1bf68bf77ba8a foreign KEY (teacher_id) references teacher (ID) 21:10:37,588 DEBUG ORG.HIBERNATE.TOOL.HB M2ddl.         Schemaexport:377-alter Table t_s Add index Fk1bf68aedc6fea (student_id), add constraint Fk1bf68aedc6fea Foreign keY (student_id) references student (ID) 21:10:38,263  INFO org.hibernate.tool.hbm2ddl.schemaexport:268-schema Export complete

Let's take a look at the generated t_s table and the field names inside should be able to understand the role of @JoinTable
It is the table name and field of the third table that is specified when Manytomany.
Joincolumns refers to the field name of the class that points to itself
Inversejoincolumns inverse is the reverse meaning, so this tag is the field that executes the other class.
What would it look like if you didn't @JoinTable the label? Let's try it for ourselves.
In addition, the above code is from the teacher to the students, we try again from the students to the teacher.


Many-to-many bidirectional associations

In the example above
Change the student and add a teacher reference to it.

Package com.bjsxt.hibernate; @Entitypublic class Student {    private int id;    private String name;    Private set<teacher> teachers=new hashset<> ();        @Id    @GeneratedValue Public    int getId () {        return Id;    }        Remember the two-way time to add Mappedby    @ManyToMany (mappedby= "students") public    set<teacher> getteachers () {        return teachers;}    }


GLT likes DLF

DLF Likes GLT

Onetoone



Hibernate 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.