Hibernate deep learning notes

Source: Internet
Author: User

Hibernate deep learning notes

 

I have seen it at the very beginning of Hb's fire, but I am not very familiar with ormaping. Now I want to re-read HB. In the past, many places that were not very familiar with it have been suddenly enlightened.

· The increment identifier generator is used by hibernate to generate a primary key in an incremental manner.

· The identity generator is used by the underlying database to generate primary keys. This is mainly used for databases that support auto-increment fields as primary keys.

· The sequence identifier generator generates the primary key from the sequence provided by the underlying database

· Native ID generator selects whether to use increment, identity, or sequence to generate a primary key based on the underlying database.

· The database is a one-to-one or many-to-one relationship. If it is a one-way association, it is generally used to design the association relationship.

· If the fields in the database and the attributes of the Java class are in a one-to-one relationship, the HBM file uses the property element for representation. Otherwise, other elements will be used for representation, for many-to-one instances, use the allow-to-one element. for one-to-many instances, use the set element, such as the multi-to-one association between orders and users, there is a customer attribute in order, but the database order table does not have the corresponding field of customer. When writing an HBM file, use the allow-to-one element, if there is a one-to-many relationship between the user and the order, the customer has an orders attribute, but the database customer table does not have a field such as orders, you need to use the set element when writing the HBM file.

· The association between tables and Java classes must be determined based on actual needs. When you need to find multiple parties based on one party, you can create a ing between multiple parties and one class, if one party needs to be obtained based on multiple parties, one-to-many ing needs to be established.

· When setting two-way Association, you must set both the customer and order, for example, write: customer. addorders (order); Order. setcustomer (customer); after this is done, when HB finds that the customer has changed, an update statement is generated. If order also changes, another statement is generated. to improve performance, you need to set inverse to true. In this way, an update statement is executed only according to the status changes of multiple parties when two-way associations are set.

· If cascading deletion is required, set cascade = delete on multiple sets. In addition, this deletion only deletes relevant records in the database, at this time, the Persistent Object still exists in the memory, but it is no longer associated with the records in the relevant table and becomes a temporary object.

· In a one-to-many relationship, if the cascade attribute of multiple sets is set to nnoe, the association between a child object and its parent object is removed, in the database, only the foreign key of the sub-table is set to null. If cascade is set to all-delete-orphan, the corresponding records in the sub-table are deleted.

· The session commit method will call its flush method to clean up the cache. Generally, we do not need to call the flush method, as long as we call commit.

· Three states of objects in HB: temporary (instantaneous) state, newly created, not in session cache; Persistence State, already in session cache; Free State, already persistent, there is a corresponding record in the database, but it has been cleared from the session. The Persistence State of the object is related to a session. Therefore, it is necessary to avoid the association of a persistent object by two sessions.

· Session can be said to be the most important object in Hb. It provides a series of important methods.
The SAVE () method is used to convert a temporary object into a persistent object. Therefore, it is meaningless to pass a persistent object or an object in the Free State to save as a parameter, the former does not do anything, and the latter adds a record.

· Session execution of the SAVE () method does not immediately execute the SQL statement. The SQL statement is executed only when the cache is cleared. Therefore, if the persistence object is modified after the save operation, an update SQL statement is generated. Therefore, all modifications must be placed before the Save method.

· The update () method converts an object in the Free State into a persistent object. The update SQL statement is executed only when the session is refreshed, therefore, only one SQL statement is generated for multiple modifications to the free object. Even if no attributes of the Free object are modified, an update SQL statement is generated during update, if the select-before-update attribute is set to true in the HBM file, a SELECT statement is executed before the update is executed, and the result is compared with the current object, execute the update statement if any change occurs.

· If a persistence object with the same OID as the free object to be added exists in the cache, an exception will be thrown during update.

· The saveorupdate method () of the session includes both the SAVE and update functions. If a free object is passed in, the update method is called. If a temporary object is passed in, the update method is called, if it is a persistent object, the system directly returns

· Hb considers an object as a condition for a temporary object. The id value is null; the version attribute is null; the ID has the unsaved-value attribute, and the ID is consistent with the value; intercepter class specified, and isunsaved returns true

· The load method and get method will return a Persistent Object Based on the given ID. The difference is that no corresponding record is found in the database. The former will throw the obejctnotfoundexception exception, and the latter will return null, load returns the proxy object of the object class, And get returns the object class. If load is found in the first-level cache and cannot be found, it will be found in the second-level cache, get will only search in the first-level cache.

· The delete method will delete a persistent object. If a free object is deleted, Hb will change it to a persistent object and then delete it, the SQL statement for deleting records is generated only when the cache is cleared, and the deletion object is cleared from the session when the session is closed.

· When using the cascade ing such as set and sequence-to-one, you need to set the cascade attribute to perform different cascade operations.

· If a trigger is used in the database, the object obtained by the session and the database will not be consistent when Hb is used. In this case, you need to use the refresh () of the session to retrieve the object again immediately, get the updated object after the trigger is executed

· Hb interceptor can be seen as a database trigger

· Hb custom type, simply put, is to use the resultset to convert the type of the value obtained from the database to obtain the final required type, and insert it to the database, convert the value again and add it to the database using statement.

· When customizing data types, you must define custom types as unchangeable.

· To avoid unnecessary access to the database, Hb uses two retrieval strategies: delayed retrieval (to avoid unnecessary associated retrieval) and force left join (use an SQL statement to retrieve the current object and associated object at the same time)

· Retrieval can be classified into category-level retrieval and association-level retrieval.
· Class-level retrieval is like this. When the load and get methods of the session are executed, the corresponding objects are obtained immediately or by delay, in HBM files, the lazy attribute is set to false and true on the class element. The latency is like this, And an object is not returned, instead, you only obtain the oId property value to generate a very simple proxy object that inherits the ing object (cglib is used for this ), the SQL statement is executed to obtain all the attributes of the object only when you really need to access the attributes of the object.

· Class-level delayed loading will have the following impact on some session behaviors. if the object is not found in the load, objectnotfoundexception will not be thrown, this exception is thrown only when the get method of this object is used. If the Persistent object is not subjected to any get operation after the load operation, and then it becomes a free object, in this case, except for the ID value (the get method of the ID will not cause the proxy class to be instantiated), the other values are inaccessible. the get method accessing these attributes throws an exception, and the initialize method of hibernate immediately initializes the proxy class.

· Delayed loading is only valid for laod and is invalid for get and find. Therefore, get will never generate a proxy class for the ing Class.

· Principle of batch instant retrieval: the batch-size attribute of set is used to locate the records of the master table in the case of multiple-to-many and one-to-many associations, when searching for records in the associated table, how many primary table IDs are used at a time to perform the query. By default, each time a record ID in the primary table is used to find the corresponding records from the table, such SQL statements will increase significantly, and the use of batch-size will reduce the number of queries from the table

· Force the left join to be valid only for the get method and not for the find method. After the set outer-join is set to true, HB uses a statement to obtain related records in the master-slave table.

· For multi-to-one or one-to-one associations, the external connection retrieval policy should be used first, which is less than the SQL statement used in the immediate retrieval policy.

· If the number of external join tables is too large, the retrieval performance will also be affected. You can set the number of left linked tables by setting the max_fetch_depth value of hibernate, the setting of this value depends on the number of records in the table and the performance of external database connections.

· For one-to-one association, if you want to use a delayed loading policy, you must set the value of constrained in one-to-one to true.

· Hb can be searched through the object graph navigation (Session load and get methods), and through hql (the query methods of session find and query are recommended, and the latter is preferred ), search by QBC (by using criteria as an object), search by QBE, and search by local SQL

· In QBC, you can use this to reference the current instance.

· Hql and QBC support polymorphism. For example, from Java. Lang. Object and from Java. Io. serializable can be used to locate all the instances and implement the serializable interface.

· Implement paging query in hql and QBC
· Hb provides two methods to implement paging query. The first method is setfirstresult (INT firstresult), which specifies the object to be retrieved. The firstresult parameter indicates the index position of the object in the query result. the default value is 0. setmaxresult (INT maxresults) sets the maximum number of records retrieved for the first time.

· Note that many methods in Hb support the method chain programming style.

· Use the list () method to retrieve multiple objects and use the uniqueresult () method to retrieve a single object. If multiple objects can be returned by a query, use setmaxresult (1) set the returned result to 1, and then call the uniqueresult () method.

· Bind location information to parameters. There are two methods to bind the Hb parameter. One is to add the parameter name with a colon, and then use setxxxx ("parameter name", parameter value ), what is another method used in hql ?, Then use setxxxx (serial number, parameter value );

· There are also three methods to bind parameters: setentity ("parameter name", persistence or free object) and setparameter ("parameter name", parameter value, HB ing type name). The last one is to bind the parameter name to the property of an object, for example, "from customer as c Where C. name =: Name and C. age =: Age ", setproperties (customer) will bind the name and age attribute values of the customer object to the name and age parameters in hql

· If hql statements are complex, we recommend that you write hql statements in the HBM ing file in the format of <query name = "queryname"> <! [CDATA [query string] </query>, which is in parallel with the class node definition.ProgramThe query statement is obtained through the getnamedquery () of the session. This method is a good choice for maintainability and readability. if it is a local SQL statement, you need to write it like this: <SQL-query name = "queryname"> <! [CDATA [query string]> </SQL-query>. All query statements are obtained using the session. getnamedquery () method.

· Note in writing hql search statements: to query records whose names are null in all customer tables, you need to write "from customer as c Where C. name is null ", but cannot be written as" from customer as c Where C. name = NULL ", because no matter what the name value is, C. name = NULL does not return true or false, but null

· The query statements in hql are case-insensitive. QBC does not support direct calling of SQL functions and does not support mathematical operations.

· The range operation in hql is similar to that in SQL, using between... and in (N1, N2, N3 ...)

· The fuzzy query in hql is similar to SQL. One is %, which indicates any length and any character. If it is Chinese, two % must be given, and the other is an underscore, for example, to query all customers whose strings start with T and have a length of 3: "From customer C Where C. name like't _ '", for a complex point, all records whose names start with T and end with M" from customer C Where C. name like 't%' and C. name like '% m '"

· Connection query in hql. If "left join fetch" is used in the hql statement, the search policy formulated in the ing file will be ignored and the search policy for pressing left join will be used, for example: "from customer C left join fetch C. orders O where c. name like't % '". one bad thing about using urgent external connections is that if the slave table has multiple records associated with one record in the master table, it will get repeated records in the master table, to filter records in the master table, use hashset for filtering.

· The keyword of left Outer Join in Hb is left join, which is the same as the SQL statement generated by pressing left join. The difference is that the returned object is an array, the first is the object instance mapped to the master table, and the second is the associated table ing instance, such as the Association between customer and order. Each instance returned by the list is an array containing a customer and order instance, if the set order search policy is delayed, the customer is being executed. when the getorders () method is used, the corresponding SQL statement is generated, but the corresponding order is obtained from the session cache instead of actually accessing the database.

· Generally, we write hql statements starting with form. Of course, we can also start with select. There is no difference between writing and not writing select statements in a single table operation. If it is a multi-table join operation, pay attention to it, if the SELECT statement is not written, the ing instance between the master table and the associated table will be returned at the same time. However, if the SELECT statement is written, only the specified ing instance object will be returned.

· The keyword of inner join in Hb is join or inner join. in SQL, records existing in both tables are retrieved. In hql, the record is the same as the left join. The returned object array is a set of objects.

· The inner join fetch keyword is urgently used. Like the urgent left join, the retrieval policy in the ing file is ignored to retrieve instances in the master table and associated table at the same time, and duplicate records are also included.

· If you only need some attributes of the instance, you need to use select in hql. The returned results can also be encapsulated into a JavaBean and used directly in hql. For example: select New customrow (C. ID, C. name, O. ordernumber) from customer C join C. orders O where C like't % '. customerrow is a custom JavaBean. It encapsulates the query results and can be accessed directly in the returned results.

· If you only need to retrieve part of the data in the set, you can also use the createfilter (collection, hql) of the session in addition to specifying it in hql. The first parameter is the set, the second hql statement that needs to be filtered, such as session. createfilter (customer. getorders (), "where this. price & gt; 100 order by this. price ")

· In Hb, the local SQL statement is used to include {} when the application instance attribute appears in SQL, such as session. createsqlquery ("select CS. ID as {C. id}, CS. name as {C. name} from custom CS where CS. id = 1 "," C ", customer. class)

· In general, we use list when getting a query set. However, in some cases, using the iterate method can be optimized. For example, all records of a set already exist in the cache, when iterate () is used for retrieval, only the SQL statement for getting the oId set is generated, and the required record is obtained from the Buffer Based on the oId set. If it does not exist, go to the database to find

· Transaction Management in Hb. Although one session can correspond to multiple transactions, it is recommended that one session correspond to one transaction and only one uncommitted transaction is allowed.

· Database lock Definition

· Shared locks are used to read data. They are not exclusive, but other transactions are not allowed to perform update operations. When a SELECT statement is executed, the locks are applied, and the execution is completed and unlocked.

· Exclusive lock: other transactions of locked resources cannot be read or modified. When an insert, update, or delete operation is executed, the lock is applied and the transaction ends and is unlocked.

· Update locks can coexist with shared locks. They are upgraded to exclusive locks only when the update operation is executed.

· As a deadlock occurs, other transactions wait for the exclusive lock of a transaction to be released, and the waiting transaction requests to wait for the transaction to release the exclusive lock. Such a request Loop

· Session cache is a level-1 cache, and sessionfactory cache is a level-2 Cache

· The clear and evict methods can be used to clear the cache for the first-level cache in the session. However, this method is generally not recommended because it cannot improve the performance, the viect method is used to update and delete data in batches. generally, you need to execute the session first. flush () and then execute the session. evict () method. in this case, the common practice is to bypass Hb and execute it directly through SQL. The practice is: Tx = session. begintransaction (); connection con = session. connection (); preparesatement stmt = con. preparestatement ("update... "commandid stmt.exe cuteupdate (); Tx. commit ();

· In hb2.1, the update method can only update one record at a time and cannot perform batch update. The Delete () method is the same. HB will load the deleted record to the cache first, it is not recommended to execute the delete operation.

· Hb's second-level cache is provided through a third-party cache solution and is a process-range cache.

· There is no inheritance relationship between tables, but there is an inheritance relationship between classes. To map between tables and classes, there are three ways to deal with this inheritance relationship: maps a specific class to a table, maps a base class to a table, and maps a table to each class.

· Multi-state query is also supported in Hb, which is related to the inheritance of classes. that is, to query the base class, that is, return subclass A and return subclass B. There is also a multi-state association, that is, the associated sub-table corresponding to the primary Table query, the returned results include the content in sub-Table A and the content in sub-Table B.

· When a specific class corresponds to a table, in this case, there is no way to perform multi-state association or support multi-state queries. Manual processing is required, therefore, you do not need to set a one-to-many ing relationship for the ing file of the primary table. The child table must specify the ing relationship between the attributes of the parent class of the corresponding subclass and the table fields at the same time.

· When using a ing to multiple subclasses, you need to use a field in the table to differentiate different subclasses. Therefore, you do not need to create a special ing file for the subclass, in this case, the master table can perform multi-state association and multi-state query. Therefore, you can set a one-to-many ing relationship in the ing file corresponding to the master table, in the sub-table, the discriminator element must be used to tell HB that the field is used to map to different sub-classes, and subclass must be added to specify the specific sub-classes.

· The last one is that each class with an inheritance relationship corresponds to a table. The database table here describes the inheritance relationship between classes, therefore, the multi-state association and multi-state query between the master table and slave table can be implemented. To describe the inheritance relationship between classes in the ing file, the joined-subclass element must be used in the class element of the base class to describe the ing between the subclass and the database table.

· If you do not like to embed joined-subclass and subclass in the class and use them in separate files, you need to add extends to these elements to specify the inherited base class, in this case, the added subclass class must be added through addclass in hibernateconfiguration.

· For the selection of ing methods between inheritance relationships, If you need multi-state query and multi-State Association, you can select the ing method corresponding to the specific subclass and table. If you need to use multi-state query and association, in addition, there are not many attributes in the subclass. You can use a table to correspond to an inherited class. If you want to use multi-state query and association, and the subclass contains many attributes, A class is used to map a table.

· Set in Java indicates a set with no duplicates. list indicates that the set is sorted by index and has duplicates.

· The treeset set sorts the objects added to it. Therefore, the added elements must implement the comparable interface. Otherwise, an exception is thrown when the add method is executed.

· Hashset is sorted Based on the hashcode of the set elements, which has good access performance. treeset is sorted Based on the comparable interface implemented by the set elements, or by the comparator sorting rules.

· Elements added to the treeset are not sorted again after they are modified. The most suitable sorting type is an immutable class (its attributes cannot be modified)

· List sorts the elements in the set by index. If you want to sort the elements in the Set in a natural or custom way, you can use the sort (list), sort (list, comparator) method to handle

· Set ing in Hb. In Hb, the set type in Java corresponds to the set element in the ing file. If a field value (non-primary key) cannot be repeated, you should consider using set. if duplicates are allowed, you can use bag, which corresponds to the list in Java, and the corresponding element in the ing file is idbag, which contains the collection-ID sub-element, used to indicate the primary key of the child table. although idbag allows duplicate entries, it does not sort by index. If you want to sort by index, you can use list, and you must use a field in the table to save the index order, the corresponding element in the ing file is list. Compared with set, an index sub-element is added. if the object contains a map sub-object, Hb uses the map element in the ing file to correspond to it. This element has an index sub-element, is used to specify the table field corresponding to the map key value.

· Hb provides two attributes to specify different sorting methods for sorting sets. One is to use sort to sort data obtained from the database in memory, one is to sort data directly in the database through the order-by attribute. If the data is sorted in memory (for set and map), you can specify natural for sort, indicates sorting in a natural way. If you specify a fully qualified class name that implements the comparable interface, the class name is sorted in the specified way. However, when you use the memory for sorting, the Java Collection class of the corresponding object must implement the sub-classes of the sortedset and sortedmap interfaces, because Hb is converted internally. Otherwise, an exception occurs in the shape.

· Ing one-to-one association. One-to-one association can be processed in two ways: foreign key ing and primary key ing, the foreign key ing is the one-to-one association between the primary key of the table and the foreign key of the table. In the HBM file, in the ing of the master table, use allow-to-one to specify the ing from the slave table, and set unique to true. In the ing of the slave table, you can use one-to-one to specify the ing between the slave table and the master table. In this way, two-way Association ing between the master and slave tables is established, however, only one-to-one ing from the table to the main table can be established at a time. The default one-to-one association ing adopts the search policy of urgent left join. This should be the case if you think about it.

· If primary key ing is used, that is, the primary key of the slave table is the same as that of the master table, and the master table does not have a foreign key of the slave table, in this case, the ing file of the master table should use one-to-one to set the ing relationship with the slave table, you must also use one-to-one in the table to establish a ing relationship with the master table, and set contrained to true, at the same time, the primary key policy of the slave table must use the foreign keyword to indicate that the primary key of the slave table is the same as that of the master table.

· Ing one-way, many-to-many associations. In the database, multiple-to-many associations must be processed using an intermediate table. Therefore, you must use set in the ing file to establish a ing with the intermediate table, at the same time, the cascade attribute must be set to save-update and cannot contain cascading deletion, because the records of the sub-table may be associated with multiple records from the table.

· Ing Bidirectional Multi-to-Multi-Association: Use set at both ends of the ing file of the master-slave table, but set the inverse attribute in the set at one end to true, in this way, the other end is responsible for processing the Association, and the master-slave ing object needs to be saved at the same time.

· In a one-to-many relationship, if one end is associated with one end, when one end is used as the primary control, it may fail to be saved because the foreign key cannot be empty. In addition, a slave table record is inserted first, then update the Foreign keys from the table with the primary key of the primary table. To solve this problem, you need to use two-way one-to-multiple (one-to-many + multiple-to-one) and grant the master control permission to one end.

· There are two types of locks in HB: Pessimistic locks and optimistic locks. pessimistic locks are implemented using database locks. They are defined in lockmode and set through criteria, query, and session, optimistic locks are used to lock the modified record, rather than locking the entire table. to lock the current modification record, a special field must be used to assist in processing, generally, the version or timestamp field is used.

· What is the difference between list and iterate collections in Hb's query? List uses an SQL statement to retrieve all records once and does not retrieve data from the cache, however, iterate first selects the IDs of all records, and then finds whether there are cached records in the cache. No corresponding SQL is executed to retrieve and persist data from the database.

· Sessionfactory in Hb is thread-safe, while session is thread-unsafe.

· HB3 provides support for dynamic models, that is, using map as the object model. In the ing file, entity-name is used to specify the object name, this approach aims to provide HB flexibility, but it also brings a negative side, so that the user can return to the development method similar to setparameter () in JDBC.

· Processing of clob and blob objects in Hb requires different processing for different databases. For example, for SQL Server, it is directly mapped to Java. SQL. clob, Java. SQL. blob type. and hibernate. createclob () and hibernate. createblob () creates a large field object and then saves it. However, Oracle needs to use another method to process it, because Oracle must first create a cursor when inserting a clob or blob record, therefore, you must first add a record with the clob or blob field being empty, and then update the clob or BLOB Object through update. The first step is to create an empty large field object, hibernate. createblob (New byte [1]), hibernate. createclob (""); after saving the null record, run the session. flush () Force commit, and then use session. refresh (entity object, lockmode. upgrade) forces hibernate to execute Selecte for update, write content to the large field object, and execute session again. save () for better versatility, you can use custom usertype to encapsulate large field object reading and writing.

· In hb2, hql can only perform query operations. In Hb3, hql can perform Delete and update operations.

· For hql that requires inner join, the effects of inner join fetch and inner join are different. The former will immediately fill the results returned from the database into the corresponding object, the latter executes the query and returns an array object for each record. The array corresponds to the ing master-slave ing object.

· For batch loading, the batch-size attribute of the class is used to set the number of conditions for batch loading. If there are multiple query statements in a session, in order to improve performance, you can combine multiple conditions into one SQL statement for execution to achieve batch loading.

· The session's find method cannot actually use the cache. It only writes to the cache but does not read it. iterate searches for matching records from the cache based on the obtained ID, and then executes the database query.

· Query cache can cache the results of query conditions. If multiple queries with the same conditions are executed, the query will only be accessed for the first time, and the subsequent query will be directly read from the cache, however, it has two display conditions, which must be completely consistent with the SQL statement. The database table corresponding to the two queries has not changed. By default, this function is disabled in Hb, if you want to enable it, you must set hibernate. cache. use_query_cache attribute is true
And the following query. setcacheable (true) method must be executed each time a query object is created.

 

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.