"Hibernate Step by Step"--many-to-many mapping specific explanations

Source: Internet
Author: User

In the previous article, we discussed the one-to-many mappings in detail, so there are a lot of problems in unidirectional association mappings in a-to-many mappings, so it is not recommended to use a two-to-many mapping to consider using bidirectional correlation to optimize the relationship between one-to-many mappings, in fact, a single end of the < Many-to-one> tags to indicate the relationship between them, it is also necessary to use set to indicate the set mapping at one end of the object.


one, one-way many-to-many


is still discussed in the previous article format. First of all, the relationship between objects, one-way many-to-many relationship is between two objects, for example, 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 nature means that only one end can be queried to obtain and one end of the content.

In addition, because of the many-to-many relationships, the association tables between objects are generated when the relational model is generated. The actual relationship between them is the associated table, the detailed object model such as the following:


It has been said that many-to-many relationships generate an association table. In the association table to maintain the relationship between. So there is a relational table in the corresponding relational model, which holds the primary key of the two relational tables, and the primary key of the relational table is the combination of the primary keys of the other two tables. For example, with:



   1.1. Mapping

A relational table is generated in the above relational model. So in the mapping to write the corresponding property, because it is a one-way association, so the basic mapping relationship is in the original direction of the mapping, the corresponding above relationship model is to add many-to-many mappings in the t_user relationship.


1.1.1 User.hbm.xml

The <many-to-many> tag is used in the file, and the corresponding column relationship is added to the label, as you want to make it clear how the mapping between the two objects is used. And in the resulting relational table, which column is the corresponding foreign key, so to indicate in the label, and the addition of the table property in the <set> tag will indicate to generate a new table, the following demo sample added T_user_role, so a new association table will be 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 will be very easy, the corresponding mapping code such as the following:

<?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. They are corresponding to each other, in the user because of the use of <set> mapping, so in the corresponding class file also add Haseset to indicate the mapping between the relationship.


1.2.1 User.java

Class code There is nothing to discuss, the content and the previous articles of the general same, in addition to the main 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 main properties and methods, its page code is very easy to base on, do not need to join no matter what complex content.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhbmdfegluegl1/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

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:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhbmdfegluegl1/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">


1.3. Operation1.3.1 Insert Operationdemonstrates the insert operation. After the new table is created and the data is written to the table, the relational model, the most complex of which is the associated table part, involves adding multiple roles and assigning roles to the appropriate tables. So first create the relationship and save the relationship to the database, and then create the user hash table. Add the corresponding relationship in the hash table, create the user, and then add the hash table to the user, such as 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);}}


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

In contrast to the above table, a complete write test method has been written, the data written to the relationship is actually quite simple, mainly in the writing to clarify the order of the write, otherwise there will be very many null values. Also need to pay attention to the hash table part, the first need to add the corresponding hash table content, and finally write the hash table into the database.


1.3.2 Read Operation

The read operation is very easy relative to writing. Because it is a one-way relationship, it is only possible to read the contents of one end at a time. This means that the content of the role is read by the user object, such as 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);}}
Run the test method. Print the generated content such as the following:

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. It is in fact designed to maintain relationships at both ends at the same time, from whatever end can be loaded into the content at the other end. Both the implementation and the one-way start-up are the same as the <many-to-many> tags to be used.

The same as the user and role above to do the demo sample. A one-way, many-to-many, is used in the demo sample above. The difference is that the two-way relationship is used here. So add the same mapping relationship at one end of role. And a collection map is added to the corresponding object, and the code within the corresponding user does not change.


2.1 Role.hbm.xml

Because it is bidirectional many-to-many, we want to add two-way collection mappings at the same time on both ends of the object, that is, adding <set> tags to the configuration file. and add <many-to-many> tags to the label, the detailed configuration method is similar to the User.hbm.xml configuration method above. For example, the following:

<?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

The same as in a one-way, many-to-many relationship, just need to include set mapping set in the object, use set to identify the set of mappings, such as the following code:

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 the basis of one-way association mappings. It is only necessary to configure <many-to-many> at the same time on both sides of the mapping file, that is, the User.hbm.xml and User.java code and the code above do not change, so they are no longer added repeatedly.

Conclusion


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

"Hibernate Step by Step"--many-to-many mapping specific explanations

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.