JPA (4) Table-Table Association relationships

Source: Internet
Author: User

When we do database design, the most annoying is the relationship between the various tables, the correlation relationship is: one-to-many, many-to-a, one-on, and there is one-way and two-way difference.

  1. Bidirectional one-to-many and multi-pair mapping: since the two-way, then is the same kind of: two-way one-to-many relationship, there must be a relationship between the maintenance side, in the JPA specification, requires the many side as the maintenance side of the relationship (owner side), one side as the maintenance side ( Inverse side). You can specify @OneToMany annotation in one side and set the Mappedby property to specify that it is the maintained side of this association, many as the maintenance side. Specify the @ManyToOne comment in the many side, and use the @JoinColumn to specify the foreign key name, the more difficult to understand, the following is the code:

  

@OrderBy (the ID"//refers to the time to take out the data, according to which field to arrange, we are here according to the User table ID field sort, the default is ASC, full usage: @OrderBy (value= "Group_name ASC, Name DESC") @OneToM Any (targetentity=phone.class, mappedby="User"//mappedby said the above is the maintenance side, more of that end is the maintenance side, note that mappedby= "xxx" XXX represents the class in another class associated with the name of the property, in this case, the user
PublicSet<phone>Getphones () {returnphones; } @JoinColumn (Name="user_id")//Specify the foreign key @ManyToOne (targetentity=user.class)// PublicUser GetUser () {returnuser; }

Incidentally, the one-way many-to-one how to do, for the above code, we just want to use the user will be maintained annotations to remove, of course, set<phone> also need to be removed.

2. Bidirectional One-to-one mapping: 1-1 affinity relationships based on foreign keys: in a one-to-one-to-one association, you need to specify Mappedby in the @OneToOne annotation in the relational maintenance side (inverse side) to specify that it is the maintained side of this association. It is also necessary to establish a foreign key column on the relationship maintenance side (owner side) to point to the primary key column of the relationship's maintained side.
  

User.java:
@OneToOne (mappedby="User")//Because we need to specify that one party is a maintained segment, we set the user to be maintained segment Publicfirstlover Getfirstlover () {returnFirstlover; } Firstlover.java://using Onetoone for one-to-one mapping, name represents the foreign key of the relational table, note that this foreign key is the primary key of the maintained segment, so it is Unqie@JoinColumn (unique=true, name="user_id") @OneToOne PublicUser GetUser () {returnuser; }

In association relationships, lazy loading is often a problem we consider, and can be used in our example, using:

    @JoinColumn (unique=true, name= "user_id")    @OneToOne (Fetch=fetchtype.lazy)      Public User GetUser () {        return  user;    }

However, there is a situation where the user can not associate Firstlover (because the foreign key is defined in the Firstlover table), if there is a Firsetlover association is set as the proxy object and deferred loading, if there is no associated firsetlover set NULL, Hibernate does not read the Firsetlover table is not able to determine whether there is an association with Firsetlover, so can not be determined to set NULL or proxy object, and unified set as a proxy object, also cannot satisfy the non-associative situation, so can not use lazy loading, only explicit read Firsetlover.

The last one is the case of many-to-many relationships, in a bidirectional many-to-many relationship, we must specify a relationship maintenance side (owner side), which can be identified as the relationship maintenance side by specifying the Mappedby attribute in the @ManyToMany annotation. For testing, I have defined two classes:

Student.java:package com.hotusm.commom.entity;import Java.util.hashset;import java.util.set;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.id;import Javax.persistence.joincolumn;import javax.persistence.jointable;import javax.persistence.ManyToMany; @Entity Public classStudent {PrivateInteger ID; PrivateString name; PrivateString sex; PrivateString School; PrivateSet<teacher> teachers=NewHashset<>(); @GeneratedValue @Id PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     PublicString Getschool () {returnSchool; }     Public voidSetschool (String school) { This. School =School; } @JoinTable (Name="Teach_stu",//Specifies the table name of the intermediate table, if no table name is specified, the default name is: Tab1_tab2 joincolumns={@JoinColumn (name="teacher_id",//Specifies the field name of the foreign key of the primary key of this class in the intermediate table, Referencedcolumnname="ID"},//Specifies what the primary key of this class is, in this case, the ID of Teach_stu teacher is the primary key value of this class Inversejoincolumns={@JoinColumn (name="student_id",//And above is the same meaning, indicating the name of another class primary key in the middle table referencedcolumnname="ID"//Specifies what the primary key for another class is, and here are the IDs)}) @ManyToMany//plus many-to-many markers PublicSet<teacher>getteachers () {returnteachers; }     Public voidSetteachers (set<teacher>teachers) {         This. Teachers =teachers; } @Override PublicString toString () {return  This. Name; }}teacher:package Com.hotusm.commom.entity;import Java.util.hashset;import Java.util.set;import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.id;import Javax.persistence.ManyToMany; @Entity Public classTeacher {PrivateInteger ID; PrivateString name; PrivateString subjectname; PrivateSet<student> students=NewHashset<>(); @GeneratedValue @Id PublicInteger getId () {returnID; }         Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; } @Column (Name="Subject_name")     PublicString Getsubjectname () {returnSubjectname; }     Public voidsetsubjectname (String subjectname) { This. Subjectname =Subjectname; } @ManyToMany (Mappedby="Teachers")//Specify the maintenance of the party, note that the name here is another class property name: Private set<teacher> teachers=new hashset<> ();  PublicSet<student>getstudents () {returnstudents; }     Public voidSetstudents (set<student>students) {         This. Students =students; } @Override PublicString toString () {return  This. Name; }}

Basically, there are several related relationships.

JPA (4) Table-Table Association relationships

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.