"Hibernate Step by Step"--multi-mapping

Source: Internet
Author: User
Tags object model

The previous article discusses a one-to-many mapping in detail, and there are a lot of problems with unidirectional mappings in a pair of mappings, so it is not recommended to use a two-way association to optimize the relationship if one-to-many mappings are to be considered, which is essentially using <many-to-one at the end of a pair of mappings. > tags to indicate the relationship between them, in addition to using set to indicate the set mapping in an object at one end.


one, one-way many-to-many


Still in accordance with the previous article format to discuss, first of all, the relationship between the object, a one-way multi-to-many relationship between two objects, such as between people and positions, a person can have multiple positions, and a position can be more than one person responsible, so they formed a many-to-many relationship between In addition, this unidirectional means that only one end can be queried to get the content at the other end. In addition, because there are many-to-many relationships, the association tables between objects are generated when the relational model is generated, and the actual relationship between them is the associated table, with the following object model:


It has been said that many-to-many relationships generate an association table that maintains relationships among the associated tables, so there is a relational table in the relational table that holds the primary key of the two relational tables, and the primary key of the relational table is the combination of the other two tables ' primary keys, such as:



   1.1. Mapping

The above relational model will generate a relational table, so in the mapping to write the corresponding property, because it is a one-way association, so the main mapping relationship is added in the original direction of the map, corresponding to the above relational model is to add many-to-many mappings in the t_user relationship.


1.1.1 User.hbm.xml

You want to use the <many-to-many> tag in the file, and add the corresponding column relationship to the label, because you want to have two objects to know how the mapping between them is used, and in the resulting relational table which column is the corresponding foreign key, so it is indicated in the label, and in the other The Add Table property in the <set> tag indicates that a new table is to be generated, and T_user_role is added to the following example, so a new association is generated.

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

1.1.2 Role.hbm.xml

Because it is a one-way relationship, there is no need to add extra tags in the mapping file to maintain the relationship, its internal code is also very simple, the corresponding mapping code is as follows:

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">



  1.2. class Files

The code in the class file is written in the same way as the mapping file, and they correspond to each other, and in the user because the <set> mapping is used, the Haseset is added in the corresponding class file to indicate the mapping relationship.


1.2.1 User.java

Class code There is nothing to discuss, the content and the previous articles are roughly the same, in addition to the basic properties and methods need to add the corresponding hashset.


Package Com.src.hibernate;import Java.util.set;public class User {//id, private int id;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Name private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} Role Collection Private Set Roles;public set GetRoles () {return roles;} public void Setroles (Set roles) {this.roles = roles;}}

1.2.2 Role.javaThe basic properties and methods, its page code is very simple base, do not need to add any complex content.

Package Com.src.hibernate;public class Role {//id marked private int id;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Name private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;}}

The resulting table structure is as follows:



1.3. Operation1.3.1 Insert OperationTo demonstrate the insert operation, the new table is written to the table after the data, corresponding to the relational model, in the relational model is the most complex association table part, need to add multiple corresponding roles, and assign the role to the corresponding table, so first to create a relationship and save the relationship to the database, and then create a user hash table, Add the corresponding relationship in the hash table, create the user, and then add the hash table to the user with the following code:

public void Testsave () {Session session=null;try{//Create Session object Session=hibernateutils.getsession ();// Open transaction session.begintransaction ();//Create Role 1Role r1=new role (); R1.setname ("Doctor"); Session.save (R1);//Create role 2Role R2=new Role (); R2.setname ("Teacher"); Session.save (R2);//Create Roles 3Role r3=new role (); R3.setname ("Farmer"); Session.save (R3);// Create Roles 4Role r4=new role (); R4.setname ("Woman"); Session.save (R4);//Create Role 5Role r5=new role (); R5.setname ("Father"); Session.save (R5);//create User 1, and set the user role users user1=new user (); User1.setname ("Anne"); Set roles1=new HashSet (); Roles1.add (R1); Roles1.add (R5); User1.setroles (roles1); Session.save (user1);//create User 2, and set the user role users user2=new user (); User2.setname ("Jack"); Set roles2=new HashSet (); Roles2.add (R2); Roles2.add (R4); User2.setroles (roles2); Session.save (user2);//create User 3, and set the user role users user3=new user (); User3.setname ("Baby"); Set roles3=new HashSet (); Roles3.add (R3); Roles3.add (R2); User3.setroles (ROLES3); Session.save (User3); Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); SessiOn.gettransaction (). rollback ();} Finally{hibernateutils.closesession (session);}}


Execute the above test method to write the structure to the table:

Compared to the above table, a complete write test method is written, the data written to the relationship is actually quite simple, mainly in writing to clarify the order of the write, otherwise there will be a lot of null values, in addition to note that the hash table part, the first need to add the corresponding hash table content, Finally, the hash table is written to the database.
     1.3.2 Read Operation

The read operation is very simple relative to the write, because it is a one-way relationship, so the content of the other end can only be read through a single end, that is, by using the user object to read the contents of the role, the following code:

public void TestLoad1 () {Session session=null;try{session=hibernateutils.getsession (); Session.begintransaction (); User user= (user) Session.load (user.class, 1); Set users=user.getroles (); for (Iterator Iter=users.iterator (); Iter.hasnext ();) {role role= (role) Iter.next (); System.out.println ("User.name=" +user.getname () + "and Role.name=" +role.getname ());} Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}
Execute the test method and print the generated content as follows:

Hibernate:select user0_.id as id0_0_, user0_.name as name0_0_ from T_user user0_ where user0_.id=? Hibernate:select roles0_.user_id as user1_1_, roles0_.role_id as role2_1_, role1_.id as id2_0_, role1_.name as name2_0_ F Rom t_user_role roles0_ left outer joins T_role role1_ on Roles0_.role_id=role1_.id where roles0_.user_id=? User.name= Anne and Role.name= fatheruser.name= Anne and Role.name= Doctor

two, two-way many-to-many


Bidirectional many-to-many mappings can be seen as a one-way extension, in fact, to set up at both ends to maintain the relationship, from any side can be loaded to the other end of the content, in the implementation and one-way starting end is the same as the use of <many-to-many> tags.

Also with the above user and role to do the example, the above example uses a one-way many-to-many, the other is to use a bidirectional relationship, so to add the same mapping at one end of the role, and to add a collection map to the corresponding object, where the corresponding user code does not change.


2.1 Role.hbm.xml

Because it is bidirectional and many-to-many, we want to add two-way collection mappings to both ends of the object, that is, adding <set> tags to the configuration file, and adding <many-to-many> tags to the tag. The specific configuration method is similar to the User.hbm.xml configuration method above, as follows:

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">


2.2 Role.java

Same as the file in a one-way, many-to-many relationship, but you need to add set mapping set to the object, use set to indicate the set of mappings, as follows:

Package Com.src.hibernate;import Java.util.set;public class Role {//id marked private int id;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Name private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} User Collection Private Set users;public set Getusers () {return users;} public void Setusers (Set users) {this.users = users;}}

Bidirectional Association mappings are configured on a one-way association map, and can be configured at both ends of the mapping file (<many-to-many>). This means that the User.hbm.xml and User.java codes are the same as the code above, and do not change, so they are not added again.

Conclusion


Complete one-way many-to-many discussions, it is important to note that the method is configured in User.hbm.xml, requires the use of <many-to-many> tags and needs to generate a relational table to maintain many-to-many relationships, the rest of the content is very simple.

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.