A one-way association of hibernate three relational relations

Source: Internet
Author: User
Tags throw exception

One category
Hibernate relationships can be divided into: one-way and two-way associations
One-way associations include: 1->1 1->n n->1 n->n
Bidirectional associations include: 1->1 1->n n->n
Two-way N->1 Association
1. The program should add an attribute to the persisted class at one end of N, which references the associated entity at the end of the 1
For n->1 associations, you need to use the @manytoone modifier at one end of N to represent the properties of the associated entity, which can specify the following properties:
(1) Cascade: Specifies what cascade policy the hibernate uses for the associated entity, including the following five scenarios:
Cascadetype.all: Cascade all persisted operations to the associated entity
Cascadetype.merge: Cascade MERGE Operations to associated entities
Cascadetype.persist: Cascade PERSIST Operations to associated entities
Cascadetype.refresh: Cascade REFRESH Operations to associated entities
Cascadetype.remove: Cascade the REMOVE action to the associated entity
(2) Fetch: Specifies the crawl strategy when fetching the associated entity
Fetchtype.eager: Crawl Now
Fetchtype.lazy: Delayed crawl
(3) Optional: Specifies whether an association relationship is optional
(4) Targetentity: Specifies the class name of the associated entity. By default, the class name of the associated entity is judged by reflection
Note: You do not need to specify targetentity most of the time, but if you use the @onetomany or @manytomany decorated 1--n N--n Association, you must specify the Targetentity property without the generic information using the Set collection
2. N--1 Association of a non-connected table
Simply add a column of foreign keys at one end of N and let the foreign key value record the entity to which the object belongs. You can use @joincolumn to decorate the properties that represent the associated entity, which is primarily used to map the underlying foreign key columns.
Person.java
@Entity
@Table (name= "Person_info")
public class Person {
@Id
@Column (name= "person_id")
@GeneratedValue (Strategy=generationtype.auto)
Private Integer ID;
private String name;
private int age;

@ManyToOne (Targetentity=address.class)
@JoinColumn (name= "address_id", Nullable=false)
@Cascade (Cascadetype.all)
private address address;
...//Omit Getter/setter and other methods here
}
Address.java
@Entity
@Table (name= "Address_info")
public class Address {
@Id
@Column (name= "address_id")
@GeneratedValue (Strategy=generationtype.auto)
private int addressid;
Private String Adressdetail;
...//Omit Getter/setter and other methods here
}
Don't forget to configure the file Hibernate.cxf.xml Plus:
<session-factory>
<property name= "Hibernate.dialect" >org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name= "Hibernate.connection.driver_class" >com.mysql.jdbc.Driver</property>
<property name= "Hibernate.connection.url" >jdbc:mysql:///mydb</property>
<property name= "Hibernate.connection.username" >root</property>
<property name= "Hibernate.connection.password" >123456</property>
<property name= "Hibernate.hbm2ddl.auto" >update</property>
<property name= "Show_sql" >true</property>
<property name= "Hibernate.format_sql" >false</property>
<mapping class= "Myhibernate.person"/>
<mapping class= "Myhibernate.address"/>
</session-factory>
Test:
public class MyTest {
public static void Main (string[] args) {
Configuration Config=new configuration (). Configure ();
Sessionfactory factory=config.buildsessionfactory ();
Session session=factory.opensession ();
Transaction tx=session.begintransaction ();
Person P=new person ();
P.setname ("Lyy");p. Setage (22);
Address A=new address ("Beijing"); Create a transient Address object
P.setaddress (a);
Session.save (P);
Address A2=new address ("Nanjing");
P.setaddress (A2);
Tx.commit ();
Session.close ();
}
}
Note: When you save the person object, you insert an address record into the Person_info table, but when address is transient, two conditions occur: Throw exception object references an unsaved transient Instance-save the transient instance before flushing, because the primary table record is not inserted, so the reference to the record from the table record cannot be inserted; The system automatically cascade into the main table record, and then insert the record from the table. We have this line in the program: @Cascade (Cascadetype.all), which means that the system automatically inserts the primary table record first, persisting the Address object, and then persisting the person object.
3. N--1 association with connected tables
The program needs to explicitly use @jointable annotations to map the join table, and its properties are as follows:
Name: Table name of the connection table
Catalog schema Indexes uniqueconstraints the same as the others
Targetentity: Specifies the class name of the associated entity
Joincolumns: Multiple @joincolumn can be accepted to configure column information for foreign key columns in the join table that reference the primary key columns of the current entity's corresponding table
Inversejoincolumn: Multiple @joincolumn can be accepted to configure column information for the foreign key columns of the connection table that reference the primary key columns of the associated entity table for the current entity
Modify the Person.java to:
@Entity
@Table (name= "Person_info")
public class Person {
@Id
@Column (name= "person_id")
@GeneratedValue (Strategy=generationtype.auto)
Private Integer ID;
private String name;
private int age;

@ManyToOne (Targetentity=address.class)
@JoinTable (name= "person_address",/////Here Specify the table name for the join table is person_address
Specify the PERSON_ID foreign key column in the join table, referencing the primary key column of the current entity's table
[Email protected] (name= "person_id", referencedcolumnname= "person_id", Unique=true),
Specifies the ADDRESS_ID foreign key column of the connection table, referencing the primary key column of the associated entity table for the current entity
[Email protected] (name= "address_id", Referencedcolumnname= "address_id"))
@Cascade (Cascadetype.all)
private address address;
...
}
Three-way 1--1 Association
You need to use the @onetoone modifier to represent the properties of the associated entity, whose properties are:
Cascade Fetch targetentity Ibid.
Mappedby: The property's valid property value is the property name of the associated entity, which specifies which property in the associated entity is referenced to the current entity
Orphanremoval: Sets whether to delete the orphan entity. If an entity is associated with a parent entity that does not exist, that is, the foreign key of the entity's corresponding record is NULL, and the entity is called an orphan entity
Optional: Specifies whether an association relationship is optional
Person.java
@Entity
@Table (name= "Person_info")
public class Person {
@Id
@Column (name= "person_id")
@GeneratedValue (Strategy=generationtype.auto)
Private Integer ID;
private String name;
private int age;

@OneToOne (Targetentity=address.class)
@JoinColumn (name= "address_id", referencedcolumnname= "address_id", Unique=true)
@Cascade (Cascadetype.all)
private address address;
...
}
Four-way 1--n Association
The collection property is used in the persisted entity of the association, because one end of the 1 needs to access one end of N, and the end of N will appear as a collection set. We only need to increase the member variable of the set type at one end of 1, which records all the associated entities of the current entity.
We need to use the @onetomany annotation, which has the following properties:
Cascade Fetch Orphanremoval Mappedby targetentity
1. One-way 1--n association with no connection table
Person.java
@Entity
@Table (name= "Person_info")
public class Person {
@Id
@Column (name= "person_id")
@GeneratedValue (Strategy=generationtype.auto)
Private Integer ID;
private String name;
private int age;

@OneToMany (Targetentity=address.class)
@JoinColumn (name= "person_id", Referencedcolumnname= "person_id")
Private set<address> addresses=new hashset<> ();
...
}
Test:
public class MyTest {
public static void Main (string[] args) {
Configuration Config=new configuration (). Configure ();
Sessionfactory factory=config.buildsessionfactory ();
Session session=factory.opensession ();
Transaction tx=session.begintransaction ();
Person P=new person ();
Address A=new address ("Beijing");
Session.persist (a);
P.setname ("Lyy");p. Setage (22);
P.getaddresses (). Add (a);
Session.save (P);
Address A2=new address ("Nanjing");
Session.persist (A2);
P.getaddresses (). Add (A2);
Tx.commit ();
Session.close ();
}
}
Note: The above program hibernate is done with two SQL statements: An INSERT statement inserts a ADDRESS_INFO record with a foreign key null, and an UPDATE statement modifies the Address_info record just inserted, which can cause poor system performance.
1--n Association of a one-way non-connected table, because the address entity does not know the person entity it is associated with, the program simply adds the address entity to the Address collection property of the person entity, so hibernate cannot perform an INSERT into Specifies a value for the Foreign key column when Address_info. Solution: You can make a bidirectional 1--n association, or a 1--n one-way association with a joined table.
2. One-way 1--n association with connected tables
@Entity
@Table (name= "Person_info")
public class Person {
@Id
@Column (name= "person_id")
@GeneratedValue (Strategy=generationtype.auto)
Private Integer ID;
private String name;
private int age;

@OneToMany (Targetentity=address.class)
@JoinTable (name= "person_address",
[Email protected] (name= "person_id", Referencedcolumnname= "person_id"),
[Email protected] (name= "address_id", referencedcolumnname= "address_id", Unique=true))
Private set<address> addresses=new hashset<> ();
...
}
Five-way N--n Association
The one-way N--n Association is identical to the persisted code associated with the 1--n, and one end of the control relationship needs to add a set-type property, and the associated persisted instance is in the form of a collection.
Use the @manytomany annotation to decorate the collection property that represents the associated entity, with the following properties:
Cascade fetch Mappedby targetentity Similar to the previous, not introduced
, note that you cannot use Unique=true
@Entity
@Table (name= "Person_info")
public class Person {
@Id
@Column (name= "person_id")
@GeneratedValue (Strategy=generationtype.auto)
Private Integer ID;
private String name;
private int age;

@ManyToMany (Targetentity=address.class)
@JoinTable (name= "person_address",
[Email protected] (name= "person_id", Referencedcolumnname= "person_id"),
[Email protected] (name= "address_id", Referencedcolumnname= "address_id"))
Private set<address> addresses=new hashset<> ();
...
}

A one-way association of hibernate three relational relations

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.