Beginner easy to get started SSH-hibernate04 one to one many,

Source: Internet
Author: User

Beginner easy to get started SSH-hibernate04 one to one many,

In this chapter, we will learn the relationship association between hibernate, that is, one-to-one, one-to-many ), multiple-to-many ). This chapter will also be the last chapter of hibernate for beginners.

First, let's talk about one-to-one: a person corresponds to an ID card as a column.

Step 1: Create the table persion (person) and card (ID card). The structure of the table is varchar given by the following two PIDs to use uuid in the primary key generation policy.

Step 2: create two entity classes under project/com. entity, which correspond to the database, encapsulate the structure, and remove the pid from the parameter structure. Create hbm. xml files for these two classes, and change the primary key generation policy in the <id/> node to uuid in persion. hbm. xml.

<Id name = "pid" type = "java. lang. String"> <column name = "PID"/>
// Modify uuid <generator class = "uuid"/> </id>

Set <id/> in card. hbm. xmlThe primary key generation policy in the node is changedForeign, which is equal to the meaning of the foreign key

<Id name = "pid" type = "java. lang. String"> <column name = "PID"/> <! -- Change the primary key generation policy to a foreign key --> <generator class = "foreign"> </generator> </id>

Step 3: create a one-to-one relationship: first define a card object in the persion object class, remember not to instantiate (new), and then encapsulate it.

private Card card;
public Card getCard() { return card; } public void setCard(Card card) { this.card = card; }

Then go to the cardDefine a persion object in the object classDo not instantiate (new) and encapsulate it.

    private Person person;    public Person getPerson() {        return person;    }    public void setPerson(Person person) {        this.person = person;    }

Step 4: configure a relationship. Add the <one-to-one/> node to the persion. hbm. xml <class/> node. The value of name is the variable name of the card object defined in the persion object class.

    <one-to-one name="card" class="com.entity.Card" cascade="all"></one-to-one>

In card. hbm. xml<Class/> Add <one-to-one/> nodes to a node;The property value of name is the variable name of the persion object defined in the card object class.

<one-to-one name="person" class="com.entity.Person"></one-to-one>

Also inCard. hbm. xmlAdd a parameter <param/> to the primary key generation policy. The attribute value of name is fixed, and the persion isThe variable name of the persion object defined in the card object class.

<Id name = "pid" type = "java. lang. String"> <column name = "PID"/> <! -- Change the primary key generation policy to a foreign key --> <generator class = "foreign"> <param name = "property"> person </param> </generator> </id>

The configuration is complete here. So some people will have questions?

In persion. hbm. xml, what does cascade = "all" in <one-to-one/> mean?

The cascade attribute is equivalent to the association attribute of the two tables. It has the following attribute values:

None: No association operation is performed in all cases. This is the default value.

All:Perform Association operations in all cases

Save-update: perform join operations when you execute save/update/saveOrUpdate.

Delete: perform join operations when executing delete.

All-delete-orphan: When an orphan node is generated in the object graph, it is deleted from the database.

Take delete as an example. When the persion object data is deleted, the corresponding card object data will also be deleted.

Step 5: add the ing relationship of the object class. hbm. xml in the hibernate. cfg. xml configuration file. <mapping/>

<mapping resource="com/entity/Card.hbm.xml" />        <mapping resource="com/entity/Person.hbm.xml" />

Step 6: start the Test: Create a Test class and write a junit @ Test method.

Now that @ Tset is used, use @ Before (triggered Before method execution) and @ Aafter (triggered after method execution ), in this way, we can write repeated code in these two methods to reduce the amount of code.

private Configuration configuration;

private SessionFactory factory;

Private Session session;


Private Transaction transaction;



@Before public void Before() { configuration = new Configuration().configure(); factory = configuration.buildSessionFactory(); session = factory.openSession(); transaction = session.beginTransaction(); }

 

@ After public void after () {// close seeion session. close (); // close SessionFactory factory. close ();}

Add: add values to each other)

@ Test
Public void add (){

// Add Person p = new Person ("Haha"); Card c = new Card ("431088192215523305"); Set p. setCard (c); c. setPerson (p );
//This is becauseCascadeAssociation, so you only need to add the link.Session. save (p); transaction. commit ();
}

Query:

// Query Person p = session. get (Person. class, "4028abee5f2a0142015f2a0144280000"); System. out. println (p + "--" + p. getCard ());

I will not test the rest.

Next we will describe one-to-many: taking a province with multiple cities as an example.

Step 1: create two tables, province and city. The table structure is as follows:

Step 2: create two entity classes under project/com. entity, which correspond to the database, encapsulate the structure, and remove the table primary key from the parameter structure. Create hbm. xml files for these two classes, and change the primary key generation policy of the <id/> node to uuid in province. hbm. xml and city. hbm. xml.

Step 3: define and instantiate a multi-terminal set of city in the object class of province (one end). set and list take set as an example. Then encapsulate it.

    private Set<City> cities = new HashSet<>();         public Set<City> getCities() {        return cities;    }    public void setCities(Set<City> cities) {        this.cities = cities;    }

 

Step 4: Define the province (end) object and encapsulate it in the city (Multi-terminal) object class. Note: In this case, you need to remove the pid (the foreign key at one end of the table in the multiport table) Attribute from the entity class of the city table (which still exists in the Database Table), because the definedThe province object. Remove the <property/> node of the pid generated in city. hbm. xml!

     private Province province;     public Province getProvince() {        return province;    }    public void setProvince(Province province) {        this.province = province;    }

 

Step 5: In hbm. xml at one end<Class/> nodeAdd the following code:

<! -- Name: the multi-end set name defined in the class at one end. table name -->
<Set name = "cities" table = "city" inverse = "true" cascade = "save-update"> <key> <! -- One end (province) primary key name --> <column name = "pid"/> </key> <! -- Fully qualified name of Multi-terminal class (city) --> <one-to-specific class = "com. entity. City"/> </set>

Add the following code to the <class/> node of hbm. xml on multiple ends:

 

<! -- Name = "define the set name at one end in a multi-terminal class" class = "full-qualified class name at one end" --> <role-to-one name = "province" class = "com. entity. province "> <! -- Foreign key names (primary key names at one end) in a multi-terminal table --> <column name = "pid"/> </role-to-one>

 

Step 6: add the ing relationship of the object class. hbm. xml in the hibernate. cfg. xml configuration file. <mapping/>

<mapping resource="com/entity/Province.hbm.xml" />        <mapping resource="com/entity/City.hbm.xml" />

 

In this way, the configuration is okay, so the question is coming again?What is inverse in hbm. xml <set/> at one end?

 

Inverse: controls the link. The default value is false, that is, both ends of the link can be controlled. However, this may cause some problems. During the update, the link is controlled at both ends, so the update is repeated. Generally, one end must be set to true. The maintenance relationship of SQL statements is operated on multiple terminals.

 

Step 7: Test: @ Test is the same as the one-to-one Test method.

Added:

 

Province p = new Province ("Hunan"); City c = new City ("Changsha"); City c1 = new City ("Zhuzhou "); city c2 = new City ("Xiangtan"); // sets p for each other. getCities (). add (c); p. getCities (). add (c1); p. getCities (). add (c2); c. setProvince (p); c1.setProvince (p); c2.setProvince (p); session. save (p); transaction. commit ();

 

Query:

City c = (City) session. createQuery ("from City where cname =? "). SetParameter (0," Changsha "). uniqueResult (); System. out. println (c. getProvince (). getPid ());

Other methods will not be tested.

Finally, we will describe multiple-to-many: multiple roles correspond to Multiple permissions,MultiplePermissionMultipleFor example:

Step 1: Create a table as follows: role table (users), permission table (role), and an intermediate table (users_role). The table structure is as follows:

 

Step 2:Create two entity classes under project/com. entity. The intermediate table does not need to be used. It corresponds to the database and then encapsulates the structure. The table primary key is removed from the parameter structure. Create hbm. xml files for these two classes, and change the primary key generation policy in the <id/> node to uuid in hbm. xml.

Step 3: define and instantiate the set of the other object in these two object classes. (set and list) use set as an example. Then encapsulate it.

Step 4: Add the following code to users. hbm. xml:

// Name = set Object name table = intermediate table name
<Set name = "roles" table = "users_role" inverse = "true" cascade = "save-update">
// The primary key name <key column = "uid"> </key>
// The full path name of the object in the calss set column foreign key name (the primary key name of the object in the set) <allow-to-convert class = "com. entity. role "column =" rid "/> </set>

Add the following code to role. hbm. xml:

 
// Name = set Object name table = intermediate table name
<Set name = "users" table = "users_role" inverse = "true" cascade = "save-update">
// The primary key name <key column = "rid"> </key>
// The full path name of the object in the calss set column foreign key name (the primary key name of the object in the set) <allow-to-convert class = "com. entity. users "column =" uid "/> </set>

Step 6: add the ing relationship of the object class. hbm. xml in the hibernate. cfg. xml configuration file. <mapping/>

    <mapping resource="com/entity/Users.hbm.xml" />        <mapping resource="com/entity/role.hbm.xml" />

Last test:

Added:

Users u = new Users ("Haha"); Role r = new Role ("zombie administrator"); Role r1 = new Role ("common administrator "); role r2 = new Role ("spam administrator"); u. getRoles (). add (r); u. getRoles (). add (r1); u. getRoles (). add (r2); r. getUsers (). add (u); r1.getUsers (). add (u); r2.getUsers (). add (u );

Transaction. commit ();

Query:

Users s = session. get (Users. class, "4028abee5f664493015f6644959b0001 ");
For (Role r: s. getRoles ()){
System. out. println (r );
}

//List<Users> ls = session.createQuery("from Users u left outer join fetch u.roles r where r.rid='4028abee5f664493015f6644958a0000'").list();    //    for (Users users : ls) {     //       System.out.println(users.getRoles());    //    }

 

At this point, hibernate is over!

 

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.