008 multi-to-one association ing --- allow-to-one

Source: Internet
Author: User
  • Many to one --- allow-to-one
  • One-to-many --- one-to-many
  • One-to-one
  • Many to many --- begin-to-begin

 

Scenario:Users and groups; from the user perspective, multiple users belong to one group (Multiple-to-one Association)

The idea of using hibernate for development is to first establish an object model (domain model) and extract entities.

Currently, there are two entities: the user and the group. If multiple users belong to one group, one user corresponds to one group. Therefore, the user entity should have a reference to the holding group.

Nature of association ing:

Maps an association to a database. The so-called Association is one or more references of the Object Model in the memory.

User entity class:

Public ClassUser {

Private IntID;

PrivateString name;

PrivateGroup group;

 

PublicGroup getgroup (){

ReturnGroup;

}

Public VoidSetgroup (group Group ){

This. Group = group;

}

Public IntGETID (){

ReturnID;

}

Public VoidSetid (IntID ){

This. ID = ID;

}

PublicString getname (){

ReturnName;

}

Public VoidSetname (string name ){

This. Name = Name;

}

}

 

Group entity class:

Public ClassGroup {

Private IntID;

PrivateString name;

Public IntGETID (){

ReturnID;

}

Public VoidSetid (IntID ){

This. ID = ID;

}

PublicString getname (){

ReturnName;

}

Public VoidSetname (string name ){

This. Name = Name;

}

}

After the object class is created, create a ing file and create a simple ing file:

Group Object Class ing file:

<Hibernate-mapping>

<Class name ="Com. wjt276.hibernate. Group"Table ="T_group">

<ID name ="ID"Column ="ID">

<Generator class ="Native"/>

</ID>

<Property name ="Name"/>

</Class>

</Hibernate-mapping>

 

User object class ing file:

<Hibernate-mapping>

<Class name ="Com. wjt276.hibernate. User"Table ="T_user">

<ID name ="ID"Column ="ID">

<Generator class ="Native"/>

</ID>

<Property name ="Name"/>

<! -- <Allow-to-one> associate multiple-to-one Mappings

Name: it is a maintenance attribute (user. group), which means that a field name is added to multiple end tables,

However, the group and SQL keywords are repeated, so you need to rename the field (column = "groupid ").

In this way, this field (groupid) will be used as a foreign key to refer to the group table in the database (t_group is also called one end), that is, in the multiple

End to point to one end.

-->

<Role-to-one name ="Group"Column ="Groupid"/>

</Class>

</Hibernate-mapping>

 

※< Relative-to-one> label ※:

 

For example: <role-to-one name ="Group"Column ="Groupid"/>

 

<Role-to-one>Association ingMulti-to-one relationship

Name:Is the maintenance property (user. group). This indicates that a field name is added to multiple tables, which is called group, but the group and SQL keywords are repeated. Therefore, you need to rename the field (column = "groupid "). in this way, this field (groupid) serves as a foreign key to reference the group table in the database (t_group is also called one end), that is, add a foreign key to one end at multiple ends.

 

The following statements are generated when exported to the database:

 

Alter table t_user drop foreign key fkcb63ccb695b3b5ac

Drop table if exists t_group

Drop table if exists t_user

Create Table t_group (ID integer not null auto_increment, name varchar (255), primary key (ID ))

Create Table t_user (ID integer not null auto_increment, name varchar (255), groupid integer, primary key (ID ))

Alter table t_user add index fkcb63ccb695b3b5ac (groupid), add constraint fkcb63ccb695b3b5ac foreign key (groupid) References t_group (ID)

 

Multiple-to-one storage (the group is first stored (after the object is persistent, and then the user is saved )):

Session = hibernateutils.Getsession();

Tx = session. begintransaction ();

Group =NewGroup ();

Group. setname ("wjt276 ");

Session. Save (Group); // stores the group object.

User user1 =NewUser ();

User1.setname ("dish 10 ");

User1.setgroup (Group); // set the group to which the user belongs

User user2 =NewUser ();

User2.setname ("Joey Rong ");

User2.setgroup (Group); // sets the group to which the user belongs.

// Start Storage

Session. Save (user1); // store the user

Session. Save (user2 );

TX. Commit (); // submit the transaction

 

After executionHibernateRun the followingSQLStatement:

Hibernate: insert into t_group (name) values (?)

Hibernate: insert into t_user (name, groupid) values (?, ?)

Hibernate: insert into t_user (name, groupid) values (?, ?)

Note: If the preceding session. Save (group) is not executed, the storage fails. A transientobjectexception exception is thrown.

Because the group is transient, the Object ID is not assigned a value.

 

Result:PersistentStatus objects cannot be referenced.TransientStatus object

 

In the preceding Code operation, you must first save the group object and then the user object. We can use cascade to save the group object without having. Instead, the user object is saved directly, so that the Group can be stored before the user is stored.

The cascade attribute is used to solve the transientobjectexception exception.

Important attributes-cascade ):

Cascade means to specify the operational connection between two objects. After an object is operated, the same operation must be performed on the specified cascade object. Valid value: all, none, save_update, and delete

1. All: The Code performs cascade operations in all circumstances.

2. None: cascade operations are not performed under all circumstances.

3. Save-Update: Perform cascade operations when saving and updating

4. Delete: Perform cascade operations during deletion.

For example: <role-to-one name ="Group"Column ="Groupid" Cascade ="Save-Update"/>

Load data from multiple to one

The Code is as follows:

Session = hibernateutils.Getsession();

Tx = session. begintransaction ();

User user = (User) Session. Load (user.Class, 3 );

System.Out. Println ("user. Name =" + User. getname ());

System.Out. Println ("user. Group. Name =" + User. getgroup (). getname ());

// Submit the transaction

TX. Commit ();

After execution, the following statement is sent to the SQL statement:

Hibernate: Select user0 _. ID as id0_0 _, user0 _. Name as name0_0 _, user0 _. groupid as groupid0_0 _ from t_user user0 _ Where user0 _. ID =?

Hibernate: Select group0 _. ID as id1_0 _, group0 _. Name as name1_0 _ from t_group group0 _ Where group0 _. ID =?

You can load the group information: Because the <role-to-one> label is used, a foreign key is added to the label at multiple ends (users, point to one end (group), that is, it maintains the relationship from multiple to one, pointing to one more. When you load data of one end, it can load the data of one end. After the user object is loaded, Hibernate loads the group information to the Group attribute of the user object based on the groupid in the user object.

 

 

008 multi-to-one association ing --- allow-to-one

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.