One-to-multiple Hibernate and one-to-one hibernate

Source: Internet
Author: User

One-to-multiple Hibernate and one-to-one hibernate

One-to-many and multiple-to-one association: Add Foreign keys to multiple parties

Example: Group (one party) and User (multiple parties), a Group can have multiple users, each User can only belong to one Group

 

One-to-one Association

Create a Group object in the User (multiple parties) and add the @ ManyToOne Annotation

1. Create the Group Object Class and User object class, and add the Annotation, as shown below:

@ Entity @ Table (name = "_ group") // The group is a keyword in MySQL and cannot be directly named public class Group {private int id; private String name; @ Id @ GeneratedValuepublic int getId () {return id;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}}

 

@ Entity @ Table (name = "_ user") // to be consistent with Table _ group, use the public class User {private int id; private String name; private Group group; @ Id @ GeneratedValuepublic int getId () {return id;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}@ ManyToOne // multiple-to-one association // @ JoinColumn (name = "groupId") // specify the public Group getGroup () name of the generated foreign key () {return group;} public void setGroup (Group group) {this. group = group ;}}

 

2. Add the ing statement to hibernate. cfg. xml.

<mapping class="com.hibernate.model.Group"/><mapping class="com.hibernate.model.User"/>

3. Create a Junit test class

public class ORMappingTest {@Testpublic void test() {new SchemaExport(new Configuration().configure()).create(true, true);}}

The program has ended. Run the program, generate the table _ group and table _ user in the database, and output the table creation Statement on the console.

_ A foreign key named group_id is automatically generated in the user table, and its attribute name can be modified using the @ JoinColumn annotation.

 

One-to-multiple unidirectional Association

Creates a User (multiple parties) object in A Group (one party). This object adopts the Set form.

Add @ ManyToOne and @ JoinColumn annotations (required)

1. Create the Group Object Class and User object class, and add the Annotation, as shown below:

@ Entity @ Table (name = "_ group") // The group is a keyword in MySQL and cannot be directly named public class Group {private int id; private String name; private Set <User> users = new HashSet <User> (); // create a multi-party object in the form of Set users @ Id @ GeneratedValuepublic int getId () {return id ;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}@ onetoworkflow // one-to-many Association @ JoinColumn (name = "groupId ") // If this attribute is not added, three tables are generated in the database. Public Set <User> getUsers () {return users;} public void setUsers (Set <User> users) {this. users = users ;}}

 

@ Entity @ Table (name = "_ user") // to be consistent with Table _ group, use the public class User {private int id; private String name; @ Id @ GeneratedValuepublic int getId () {return id;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}}

2. Add the mapping statement in hibernate. cfg. xml ---- same as above

3. Create a Junit test class ---- same as above

After the program ends, the program will generate the table _ group and table _ user in the database, and output the table creation Statement on the console.

_ A foreign key with the specified attribute name is generated in the user table.

 

One-to-multiple, multiple-to-one, two-way Association

Create a Group object in the User and add the @ ManyToOne annotation. Create a User object in the Group and add the @ onetoworkflow annotation.

1. Create the Group Object Class and User object class, and add the Annotation

The User class is the same as"One-to-one Association"Part of the User class

Group class:

@ Entity @ Table (name = "_ group") // The group is a keyword in MySQL and cannot be directly named public class Group {private int id; private String name; private Set <User> users = new HashSet <User> (); @ Id @ GeneratedValuepublic int getId () {return id;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}@ OneToMany (mappedBy = "group") // The "group" here refers to the private Group group in the User class; public Set <User> getUsers () {return users;} public void setUsers (Set <User> users) {this. users = users ;}}

 

2. Add the mapping statement in hibernate. cfg. xml ---- same as above

3. Create a Junit test class ---- same as above

The program ends now,

Run the program to generate the table _ group and table _ user in the database, and output the table creation Statement on the console.

_ A foreign key named group_id is automatically generated in the user table, and its attribute name can be modified using the @ JoinColumn annotation.

 

@ MappedBy

1. You do not need to set this attribute for one-way links. This attribute must be set for two-way links to prevent both parties from setting up foreign key fields.

2. The mappedBy attribute is available only on OneToOne, oneto133, and ManyToMany. This attribute does not exist on ManyToOne.

3. mappedBy and JoinColumn/JoinTable are always mutually exclusive.

 

Taking Group (one party) and User (multiple parties) as examples,

The foreign key is in the User (multiple parties), and @ JoinColumn/@ JoinTable is only allowed in the User (multiple parties ).

Then @ mappedBy is set on the Group side ). This association is maintained by multiple users.


Lists multiple-to-many and one-to-many relationship configurations in Hibernate.

Many-to-many configuration
Party

<Set name = "A" cascade = "all" inverse = "false"
Table = "t_A">
<Key
Column = "cid"> </key>

<Role-to-define class = "ClassB"
Column = "ca"> </role-to-sequence>

</Set>
Party B
<Set name = "B" cascade = "all" inverse = "true"
Table = "t_ B">
<Key
Column = "sid"> </key>

<Role-to-define class = "ClassA"
Column = "cb"> </convert-to-sequence>

</Set>

Fetch can be set to "select" and "join"
In one to multiple

Fetch =
"Select" is to first query the objects at one end during the query, and then query multiple objects at one end. One or more SQL statements are generated;
The details are as follows: When hql is executed, a select * from tableA... will be executed first .... --> then, query tableB Based on the query result (also a query, n statements will be generated)
Fetch = "join" refers to the use of external connections for queries during queries. There is no difference between 1 + n and only one SQL statement.
When executing hql, we actually execute a multi-Table query statement select * from tableA a left join tableB .....
Cascade is simpler
Possible values of the cascade attribute are: all none save-update delete. Their meanings are as follows:
All: Join operations are performed in all cases, that is, save-update and delete.
None: No association operation is performed in all cases. The default value is none.
Save-update: perform join operations when you execute save/update/saveOrUpdate.
Delete: perform join operations when executing delete.

Hibernate: One-to-multiple, multiple-to-one relationship

Do you want one-way or two-way access?
One-way write @ many2one directly on the student's setClazz

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.