The code farmer Xiao Wang-hibernate Study 8-hibernate Association relation annotation represents @onetomany mappedby @ManyToMany @JoinTable

Source: Internet
Author: User

Recently I am also a bit depressed, exactly is the procedure to deal with the correlation relationship. Or do you just use the foreign key to deal with the association relationship? The argument is inconsistent! In a program that handles such an association relationship. To maintain such constraints on their own. Such a very optimistic kind of practice! or directly in the database to deal with such a direct foreign key association, pessimistic approach! Just saw a post. Some companies have a foreign key in the table. Handle such association relationships directly in the program. Assume that you are dealing with foreign key relationships in hibernate. We first have to have an object for the main table, and then create the foreign key. I feel a bit wordy. Why not just operate it!

I just need to know that your ID is a foreign key. Each has its own argument. I think you're thinking about it, too.

In the real world there are very few things that are pure in isolation. Most of them are purely in relation to each other. A one-way relationship can only be interviewed by the teacher. Or students visiting the teacher
or two-way relationship two can be mutual access to ask

One-way relationship
1-1
1-n
N-1
N-n
Bidirectional relationship
1-1
1-n
N-n

One-way N_1 Association is the most, many people live the same address. We just need to know his address from the people, not the users who need to know an address.

In order for us to associate two persisted entities. The program adds a property of the persisted entity at one end of N that points to the associated entity at the end of the reference 1
For N-1 (either one-way or two-way associations), it is only necessary to use @manytoone to decorate the properties of the associated entity at the end of N
There are some of the following properties, in fact I have said before, very easy to forget. See for yourself when it's okay.

Properties Description
Cascade Cascade Operations Policy Cascadetype.all ....
Fetch Crawl the associated entity's strategy, previously said Fechtype.lazy delay and immediate
Targetentity The class name of the associated entity for the attribute, by default, to obtain the class name by reflection

By default, our targetentity does not need to specify this property. But in some special cases, such as using @[email protected] to modify the 1-n N-n Association. Associated entity collection without generic information, you must specify the

Non-connected N-1

No connection is the need for a third table to maintain our relationship. For n_1 correlation, we just need to add a column of foreign keys at one end of N.

Let the value of the foreign key be recorded to the entity of the attribute.

Hibernate uses @joincolumn to decorate the attributes that represent the associated entity to map the underlying foreign key columns.

So you don't use the join table.

Okay, let's take a look at the sample.

More than one person corresponding to the same address

@Entity@Table(name="Person_inf") Public  class person {    @Id @Column(name="person_id")@GeneratedValue(strategy=generationtype.identity)PrivateInteger ID;PrivateString name;Private intAge//define the address entity associated with the person entity    @ManyToOne(Targetentity=address.class)//Map foreign key column, specify the column name of the foreign key column is address_id, different meaning is empty    @JoinColumn(name="address_id", nullable=false)@Cascade(Cascadetype.all)PrivateAddress address; ........} The Address inside is very normal for an ID. and address specific

What do they look like when they build a table?
Person_inf
PERSON_ID Age Name address_id
Address_inf
address_id Addressdetail

How to manipulate the object, since address_id is a foreign key.

Let's say we save a person object in our table. We should first have an address object.

Can be present in the database. can also be transient objects. We cascade operations at the time of insertion. The address_inf will be inserted into the table first, then the ability to use the external. Otherwise it will be error, because there is no foreign key, definitely not!

Session session = Hibernateutil.currentsession (); Transaction tx = Session.begintransaction ();//Create a Person objectPerson p =NewPerson ();//Create a transient address objectAddress A =NewAddress ("Guangzhou Tianhe"); P.setname ("Test"); P.setage ( +);//Set up an association between person and addressP.setaddress (a);//Persistent Person objectSession.persist (P);//Cascade insert operation Oh ~. Address must be inserted in the data table before the person, you have to set the cascade operation, or to error    //Create a transient address objectAddress A2 =NewAddress ("Shanghai Hongkou");//Change the persistence status of the person objectP.setaddress (A2);    Tx.commit (); Hibernateutil.closesession ();
N-1 with connections

The maintenance of our relationship is maintained by the third sheet.

For most n_1 one-way relationships, it is sufficient to maintain the correlation relationship based on the foreign key only.
Suppose there is a need to use a connection table to maintain the relationship, the program can use the connection table to display the maintenance of such relationships, the so-called junction table is to establish a third table to maintain our relationship. Using @jointable

The following is a sample of Java, in addition to these properties, we can also specify targetentity. Specifies which entity is associated with!

That is, the entity that generates the table that corresponds to which table.

@JoinTable(        name="CUST_PHONE",        //相对于当前实体的外键,的列名。

參照的列名,也就是数据表中的名字 joinColumns= @JoinColumn(name="CUST_ID", referencedColumnName="ID"), //这个也是个外键,仅仅是不说当前实体里面的属性。 inverseJoinColumns= @JoinColumn(name="PHONE_ID", referencedColumnName="ID") )

Let's see a sample.

@Entity@Table(name="Person_inf") Public  class person {    //Identity Properties    @Id @Column(name="person_id")@GeneratedValue(strategy=generationtype.identity)PrivateInteger ID;PrivateString name;Private intAge//define the address entity associated with the person entity    @ManyToOne(Targetentity=address.class)//explicitly use @jointable map to join table    @JoinTable(name="Person_address",//Specify the table name of the connection table as Person_address        //Specify the PERSON_ID foreign key column in the connection table to the primary key column of the corresponding table in the current entityjoincolumns=@JoinColumn(name="person_id", referencedcolumnname="person_id", unique=true),//Specifies the ADDRESS_ID foreign key column in the connection table, and the primary key column of the corresponding table for the associated entity of the current entityinversejoincolumns=@JoinColumn(name="address_id", referencedcolumnname="address_id")    )PrivateAddress address;
 @Entity   @Table  (name=" Address_inf ")  Public  class  address  { //Identity properties   @Id   @Column  (name=" address_id ")  @GeneratedValue  (strategy=generationtype.identity) private  int  addressid;    //a member variable that defines the address specific information  private  String addressdetail;}  

The table generated here, once the person's table does not change the address will not be changed
Just add an appearance
Person_address--table
address_id person_id
Maintaining Relationships using Connection tables

One-way 1-1 Association

It looks like 1-1 and N-1 are almost identical. You need to add a member variable that represents the associated entity in a persisted entity, no difference from the code. Because one end of N and one end of 1 can directly access the associated entity.
You need to use @onetoone to modify the properties of the associated entity, regardless of the one-way or bidirectional 1-1 Association
Have the following
Cascading operations, fetching properties. Optional whether an association relationship is optional. The class name of the target association entity targetentity. There's another important
Mappedby: The property's valid property value is the attribute name of the associated entity . This property specifies which property in the associated entity can refer to the current entity

Example: A one-way 1-1 association based on a foreign key, no join table
@Entity@Table(name="Person_inf") Public  class person {    //Identity Properties    @Id @Column(name="person_id")@GeneratedValue(strategy=generationtype.identity)PrivateInteger ID;PrivateString name;Private intAge//define the address entity associated with the person entity    @OneToOne(Targetentity=address.class)//Map a foreign key column named address_id, and refer to the ADDRES_ID primary key column for the corresponding table of the associated entity    @JoinColumn(name="address_id", referencedcolumnname="address_id", unique=true)PrivateAddress address; The address must be unique, not right! Add UNIQUE Constraint ~ ...}

There is a connection table is almost the same, understand the buy can be

@Entity@Table(name="Person_inf") Public  class person {    //Identity Properties    @Id @Column(name="person_id")@GeneratedValue(strategy=generationtype.identity)PrivateInteger ID;PrivateString name;Private intAge//define the address entity associated with the person entity    @OneToOne(Targetentity=address.class)@JoinTable(name="Person_address", joincolumns=@JoinColumn(name="person_id", referencedcolumnname="person_id", unique=true), inversejoincolumns=@JoinColumn(name="address_id", referencedcolumnname="address_id", unique=true)    )PrivateAddress address; ......}

The above things, I believe that only the first to understand can be, followed by the image of the astringent. 1-1. Must not be the same astringent.

One-way 1-n

One end of the 1 is to visit one end of N. The positive set is very similar to the previous set, but the elements in the collection today are associated entities. For a one-way 1-n association relationship.

Only a member variable of set type is added at one end of 1, and all associated entities are recorded.

You're ready. How to operate, we slowly say.

A word of the dozen can still be. Add your own understanding
@OneToMany
Cascade. Crawl, target entity, Mappedby

One-way 1-n with no connection table

1 people have a number of accommodation ~ ~ ~ Corrupt officials!

Otherwise how to buy so many houses, today's prices you do not know. Hum ~

@Entity@Table(name="Person_inf") Public  class person {    @Id @Column(name="person_id")@GeneratedValue(strategy=generationtype.identity)PrivateInteger ID;PrivateString name;Private intAge//Define all address entities associated with the person entity, without specifying the Cascade attribute    @OneToMany(Targetentity=address.class)//Map foreign key columns. The foreign key columns mapped here will be added to the corresponding data table of the associated entity. Why is it?     @JoinColumn(name="person_id", referencedcolumnname="person_id")PrivateSet<address> addresses =NewHashset<> (); ........ }
The foreign key column here is not added to the corresponding data table of the current entity, but is added to the corresponding data table of the associated entity address, a bit special!

Why. Before we used the set set, we had to add a table to remember? It's just that it's added to the associated entity.

Instead of adding a table ~ ~

The end of N does not maintain the relationship, there is no change ~

1-n with connections

@Entity@Table(name="Person_inf") Public  class person {    //Identity Properties    @Id @Column(name="person_id")@GeneratedValue(strategy=generationtype.identity)PrivateInteger ID;PrivateString name;Private intAge//Define all address entities associated with the person entity    @OneToMany(Targetentity=address.class)//Map connection table for person_address    @JoinTable(name="Person_address",//Define a foreign key column named person_id in the join table. The Foreign key column is the primary key column for the corresponding table of the current entityjoincolumns=@JoinColumn(name="person_id", referencedcolumnname="person_id"),//Define a foreign key column named address_id in the join table.         //The Foreign key column is the primary key column of the corresponding table for the associated entity of the current entityinversejoincolumns=@JoinColumn(name="address_id", referencedcolumnname="address_id", unique=true)    )PrivateSet<address> addresses =NewHashset<> ();..}

Here are 1 pairs n 1 people have multiple places to live, but each one is different, so add a unique constraint
Due to the use of the connection table, there is no maintenance connection in our person table, can be arbitrarily persisted operation.


1 person 2 adress to insert 5 operations OH
Think for yourself why?

One-way n-n is also needed.

@ManyToMany
N-n relationship must be connected to the table, and connected to the 1-n similar, but to remove the unique constraint ~
It's a direct change, the top one ~

@Entity@Table(name="Person_inf") Public  class person {    //Identity Properties    @Id @Column(name="person_id")@GeneratedValue(strategy=generationtype.identity)PrivateInteger ID;PrivateString name;Private intAge//Define all address entities associated with the person entity    @ManyToMany(Targetentity=address.class)//Map connection table for person_address    @JoinTable(name="Person_address",//Define a foreign key column named person_id in the join table that references the primary key column of the corresponding table for the current entityjoincolumns=@JoinColumn(name="person_id", referencedcolumnname="person_id"),//Define a foreign key column named address_id in the connection table,        //The Foreign key column is the primary key column of the corresponding table for the associated entity of the current entityinversejoincolumns=@JoinColumn(name="address_id", referencedcolumnname="address_id")    )PrivateSet<address> addresses =NewHashset<> ();..}

The code farmer Xiao Wang-hibernate Study 8-hibernate Association relation annotation represents @onetomany mappedby @ManyToMany @JoinTable

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.