Hibernate Study Notes and hibernate Study Notes

Source: Internet
Author: User

Hibernate Study Notes and hibernate Study Notes

V. ing One-to-multiple associations

1. Unidirectional multiple-to-one (unidirectional N-1)

1) One-Way n-1 association only needs to access one end of 1 from one end of n

① Domain model: the many-to-one-way association between Order and Customer needs to define a Customer attribute in the Order class. In the Customer class, there is no need to define the set attribute for storing the Order object.

② Relational Data Model: The mermer_id in the ORDERS table references the primary key of the CUSTOMER table (s is required for the data table at the end of multiple tables; otherwise, the table cannot be created)

2) UseAllow-to-oneIng

3) test multi-to-one ing

① Save () save

② Get () Query

③ Update () modify and delete

2. Bidirectional one-to-multiple (bidirectional 1-n)

1) bidirectional 1-n and bidirectional N-1 are identical.

2) domain model: the multi-to-one bidirectional association between Order and Customer needs to define a Customer attribute in the Order class, while in the Customer classDefine the set attribute for storing the Order object

3) Add the set relationship of n (Order) to one end of 1 (that is, the Customer ).

4) test Bidirectional Multi-to-one ing

① Save () save operation

> Ing: The n (Order) end requires regular Multi-to-one ing. The set node ing is used at the 1 (Customer) end:

Where: inverse attributes:

If inverse is set to false, it is the active party. If inverse is set to true, the active party is responsible for maintaining the association. If inverse is not set to true, the parent-child relationship is maintained on both sides.

> Test:

② Get () get operation

> Test

③ Update () Operations

6. ing one-to-one associations

1. One-to-one Association

1) Understanding: one department has only one department manager, and one Department Manager manages one department.

2) domain model: the Department has a reference to the Manager, and the Manager also has a reference to the Department.

3) ① 1-1 based on foreign key ing

> For a 1-1 association based on a foreign key, the foreign key can be stored on any side, and the external-to-one element is added at the end of the foreign key to be stored. Added to the upload-to-one element.Unique = "true"Attribute, as shown in the following figure:

> The other end must use the one-to-one element.Property-ref propertySpecify fields other than the primary key of the correlated object as the correlated Field

> Test:

Save () save:

Get:

② 1-1 based on primary key ing

> The primary key generator at one end uses the foreign policy, indicating that the primary key is generated based on the "peer" primary key. The primary key cannot be generated independently. <param> the child element specifies which attribute of the current persistence class is used as the "peer"

> The one-to-one element ing Association attribute is added at one end of the foreign primary key generator policy. The one-to-one attribute must also contain the constrained = "true" attribute; add one-to-one element ing Association attribute on the other end

Note:Constrained): Add a foreign key constraint to the primary key of the database table corresponding to the current persistence class to reference the primary key of the database table corresponding to the associated object ("peer ").

> Test:

Save ():

Get:

7. Map many-to-many associations

1. Unidirectional many-to-many:

1) domain model: the relational model between Category and Item. Only Set <Item> is defined in the Category class, that is, one-way n-n association only requires one end to use the set attribute

2) join n-n must use the connection table CATEGORIES_ITEMS.

3) similar to 1-n ing, the key sub-element must be added to the set element, and the foreign key of the CATEGORIES_ITEMS table referenced in the CATEGORIES table is C_ID. different from 1-n Association ing, when a n-n association is established, the elements in the Set use counter-to-minus. the class attribute of the sort-to-Sort sub-element specifies that the Item object is stored in the items set, and the column attribute specifies that the foreign key of the ITEMS table in the CATEGORIES_ITEMS table is I _ID.

4) for one-way, multi-to-many tests, the get () method is connected to the intermediate Table query.

2. bidirectional, many-to-many

1) domain model: the relational model between Category and Item. Set <Item> is defined in the Category class and Set <Category> is defined in the Item class, that is

Two-way n-n association requires both ends to use the set attribute

2) Two-Way n-n association must use a connection table

3) on both sides of the bidirectional n-n association, you must specify the table name of the connected table and the column name of the foreign key column. The values of the table elements of the two set elements must be specified and must be the same. The column attribute must be specified for the key and pair-to-pair sub-elements of the set element, specify the foreign key column names of the persistence class and associated class in the connection table respectively. Therefore, the column attributes of the keys and associated-classes on both sides are the same.

> Set node configuration in Category. hbm. xml:

> Set node configuration in Item. hbm. xml:

Note: For bidirectional n-n joinSet inverse to trueOtherwise, maintaining the association between the two ends may cause a primary key conflict. That is:

8. ing inheritance relationships (understanding, rarely used in development)

1. Use subclass for ing:

1) using the inheritance ing of subclass allows you to use the same table for the parent and child classes in the inheritance relationship.

2) because the instances of the parent class and subclass are all stored in the same table, you need to add a column to the table, this column is used to identify the instance of the class to which each row is recorded. This column is called a discriminator ).

3) In this ing policy, subclass is used to map subclass, And the discriminator-value Attribute of class and subclass is used to specify the value of the speaker column.

4) All fields defined by subclass cannot have non-null constraints. If a non-null constraint is added for those fields, the instance of the parent class does not have a value in those columns. This will cause a database integrity conflict, and the instance of the parent class cannot be saved to the database.

5) Specific configuration: only generate the. hbm. xml file of the parent class, and map the child classes in this configuration file.

6) test:

Save ():

Query operation:

7) disadvantages of using subclass for ing:

> Use the reporters Column

> Non-null constraints cannot be added for fields unique to child classes.

> If the inheritance level is deep, there will be more fields in the data table.

2. Use joined-subclass for ing

1) The Inheritance ing of joined-subclass elements can be used to implement a table for each subclass.

2) When this ing policy is adopted, the parent class instance is stored in the parent class table, and the Child class instance is jointly stored in the parent class table and the Child class table. Because the subclass instance is also a special parent class instance, it must also contain the attributes of the parent class instance. Therefore, the attributes common to the Child class and the parent class are saved in the parent class table. The attributes added to the Child class are saved in the Child class table.

3) In this ing policy, you do not need to use the authenticator column, but you need to use the key element for each subclass to map a common primary key.

4) You can add non-null constraints to attributes added to subclass. Because the attributes of subclass and parent classes are not saved in the same table

5) Specific ing: only generate the. hbm. xml file of the parent class, and map the subclass in this configuration file.

6) test

Save () operation:

Query () query operation:

7) Advantages:

> You do not need to use the reporters column.

> Non-null constraints can be added for fields unique to sub-classes.

> No redundant Fields

3. UseUnion-subclassIng

1) The union-subclass element can be used to map each object to an independent table.

2) attributes added to the subclass can have non-null constraints-that is, the data of the parent class instance is stored in the parent table, and the data of the Child class instance is saved in the Child class table.

3) the data of the subclass instance is only stored in the subclass table, but there is no record in the parent table.

4) In This ing policy, the fields in the subclass table are more than those in the parent table, because the fields in the subclass table are equal to the fields in the parent table, and the attributes are added to the subclass.

5) in this ing policy, you do not need to use the authenticator column or the key element to map a common primary key.

6) using the union-subclass ing policy is a primary key generation policy that cannot use identity.

7) Specific ing: only generate the. hbm. xml file of the parent class. In this configuration file, map the child classes as follows:

8) test:

Save (): Insert efficiency is also acceptable. For subclass objects, you only need to insert records into your own table.

Query (): to query a parent record, You Need To summarize the records of the parent table and the child table before performing the query.

9) Advantages:

> You do not need to use the reporters column.

> Non-null constraints can be added for fields unique to sub-classes.

Disadvantages:

> Redundant fields exist.

> If fields in the parent table are updated, the update efficiency is low.

IX. Hibernate search policy

1.Class-level retrieval policy, applicable only to the load () method of the session

1) instant retrieval (loading the objects specified by the search method immediately) and delayed retrieval (loading the objects specified by the Search Method in a delayed manner and loading the objects when using specific non-id attributes)

2) You can set a category-level search policy using the lazy attribute of the <class> element.

3) if the program loads an object to access its attributes, you can retrieve it immediately.

4) if the program loads a persistent object for the purpose of obtaining its reference only, you can use delayed retrieval. Note that an error occurred while loading resources!

5) Note: ① whether the lazy attribute of the <class> element is true or false, the get () method of the Session and the list () method of the Query always use the immediate retrieval policy at the class level.

② If the lazy attribute of the <class> element is true or the default value is true, the load () method of the Session will not execute the SELECT statement for querying the data table, and only return the instance of the proxy class object, this proxy instance has the following features:

-Dynamically generated by Hibernate using CGLIB during runtime

-When Hibernate creates a proxy instance, only its OID attribute is initialized.

-When the application accesses the non-OID attribute of the proxy instance for the first time, Hibernate initializes the proxy instance.

6) test:

2.One-to-many and multiple-to-many retrieval policies

1) Set node lazy attributes

2) Set NodeBatch-sizeAttribute

3)Fetch attribute of the Set Node

3.Multiple-to-one and one-to-one association search policies

1) set the lazy attribute of the delayed-to-one node to determine whether to delay retrieval. The default value is proxy, Which is latency retrieval. The value can be set to proxy false.

2) The lazy fetch batch-size attribute is used as follows:

10. Hibernate retrieval method (two data tables, my_department and my_employee, are created in the database using the Oracle database, and the data is imported)

Key Learning:

1.HQL(Hibernate Query Language) Retrieval Method: use an object-oriented HQL Query Language

2. HQL query HelloWorld:

3. HQLPaging Query

Two methods:

1)SetFirstResult (int firstResult): Set the start retrieval location. The firstResult parameter indicates the index location of the object in the query result.

2)SetMaxResults (int maxResults): Set how many records are retrieved at a time, that is, how many records are displayed on a page

4.HQLName query: Hql statements can be configured in the. hbm. xml file.

1) define the <query> node in the Employee. hbm. xml file to define an HQL query statement,It is tied with the <class> element.

5.HQLProjection Query: The query result only contains some attributes of an object. This is achieved using the SELECT keyword.

1) Note: The collection returned by the list () method of Query contains array elements. Each object array represents a record of the Query result.

2) The preceding method is not convenient. You can use the following method to return a set of objects for ease of use.

Note: The Employee constructor is used in hql statements. Therefore, the same constructor must be defined in the Employee class.

6.HQLREPORT query: Aggregate functions such as group by, HAVING, min (), max (), sum (), and count () can be used in HQL statements.

Supplement: You can use HQL to delete objects:

7. left Outer Join and urgent left Outer Join of HQL

1)Urgent left Outer Join (try to use urgent left Outer Join)

① Left join fetch keyword indicates an urgent LEFT Outer JOIN search policy

② The collection returned by the list () method stores references of object objects. The Employee collection associated with each Department object is initialized, and all associated Employee object objects are stored.

2) left Outer Join

① Left join keyword indicates LEFT outer JOIN query

② The collection returned by the list method stores the object array type. If you want the list collection to contain only Department objects, you can use the SELECT keyword in the HQL query statement.

8.QBC(Query By Criteria) Query and local SQL Query Criteria: standard condition

1) QBC query HelloWorld:

2) QBC queries with and or keywords

3) QBC statistics Query

4) use QBC for sorting and paging

Note: For more instances of QBC query, see the Hibernate example document:

Hibernate-release-4.3.11.Final \ documentation \ manual \ en-US \ html_single \ index.html # querycriteria

5) Local SQL query

11. Hibernate second-level cache

SessionFactory-level cache

1. Configure the level-2 cache of the Hibernate class:

> The Three jar packages added to EHCache under the hibernate-release-4.2.4.Final \ lib \ optional \ ehcache directory

> Add the EHCache configuration file hibernate-release-4.2.4.Final \ project \ etc directory, put it under the src directory

> Enable the second-level cache configuration in Hibernate. cfg. xml to use the second-level cache product settings for which class the second-level cache is used

> Note: You can also. hbm. use the cache node in the xml file to configure the cache policy, which is omitted in Hibernate. cfg. set the second-level cache for which class in xml

2. Configure the level-2 cache of the Hibernate set:

> Configure second-level cache for the collection. Note: you also need to use second-level cache for persistence classes corresponding to elements in the collection. Otherwise, n more SQL statements will be generated.

Note: You can also configure it in. hbm. xml. Note that the second-level cache of the Set is configured in the Set node.

3. Details about the ehcache. xml configuration file:

4. query cache: by default, the configured cache is invalid for HQL and QBC queries, but it can be valid in the following ways:

Note: The query cache depends on the second-level cache.

> Enable query cache in the hibernate configuration file

> Call the setCacheable (true) method of Query or Criteria.

5.Manage sessions to bind Session lifecycles to local threads

Steps (for testing ):

1) configure the Session management method in the Hibernate. cfg. xml file.

2) construct a HibernateUtils classObtains the Session bound to the current thread.

Public class HibernateUtils {// Singleton private HibernateUtils (){}
Private static HibernateUtils instance = new HibernateUtils ();
Public static HibernateUtils getInstance () {return instance ;}
Private SessionFactory sessionFactory;
// Method for obtaining the Session object public Session getSession () {return getSessionFactory (). getCurrentSession ();}
// Method for obtaining the SessionFactory object public SessionFactory getSessionFactory () {if (sessionFactory = null) {Configuration configuration = new Configuration (). configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); sessionFactory = configuration. buildSessionFactory (serviceRegistry);} return sessionFactory ;}
}

3) construct a DepartmentDao class

Public class DepartmentDao {public void save (Department dept) {/*** obtains the Session object internally and obtains the Session object bound to the current thread * advantages: 1. you do not need to input the Session object from the external. * 2. multiple DAO methods can use one transaction */Session session = HibernateUtils. getInstance (). getSession (); System. out. println (session. hashCode (); session. save (dept);}/*** if you need to input a Session object, it means that the previous layer (Service) needs to obtain the Session object. * This indicates that the previous layer must be closely coupled with the Hibernate API. therefore, this method is not recommended. */public void save (Session session, Department dept) {session. save (dept );}}

4) test:

6. We recommend that you use the native jdbc api for batch operations.

Related Article

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.