Strong man hibernate document notes

Source: Internet
Author: User
Tags jboss

Hibernate document notes are divided into three parts. The first part describes four parts: object definition, instance status, JMX integration, and JCA support.

I. object definition

1.org. hibernate. sessionfactory

For a single database, the compiled ing is a thread-safe buffer. Is the factory of a session and connectionprovider client. It has an optional process-level and cluster-level Reuse data cache (level-2 cache ).

2.org. hibernate. Session

A session object between an application and a persistent storage system with a single thread and a short life cycle. Encapsulates a JDBC connection. Is a transaction factory. It has a mandatory cache for persistent objects (level-1 cache). It is used to identify the relationship between objects and find objects.

3. persistent objects and collections

Contains short-lived, single-threaded objects in a long-running state and business functions. It can be a pojos, usually an object associated with a session (strictly speaking, a single session. When the session is closed, it is separated from the session and can be freely used anywhere at the application layer. (That is, it is used as a transmission object ).)

4. Transient and detached objects and collections

A persistent instance that is not associated with the current session. They can be instantiated by applications without persistence or closed sessions.

5.org. hibernate. Transaction (optional)

An application is used to specify a single-thread, short-lived object for atomic operations. Abstract programs for low-layer JDBC, JTA, and CORBA transactions. In a similar case, a session can span multiple transactions at the same time. Transaction Division. You can use both the lower-layer APIs and transaction.

6.org. hibernate. Connection. connectionprovider (optional)

The factory of the JDBC connection pool or JDBC connection pool. The abstraction program of the lower-layer datasource and drivermanager.

This object is not exposed to applications, but applications can be inherited and implemented by developers.

7.org. hibernate. transactionfactory (optional)

The factory of the transaction instance. This object is not exposed to applications, but applications can be inherited and implemented by developers.

Ii. instance status

Persistence objects can be in three different states according to the definition of persistence context. The Hibernate Session object is a persistent context.

1. Transient

Does not associate any persistence context. There is no persistent identifier (the primary key value ).

2. Persistent

Associated with the current persistent context. It has a persistent identifier. In most cases, there are corresponding rows in the database. For a specific persistence context, Hibernate ensures that the persistence identifier is the same as the Java identifier (location of the object in memory.

3. Detached

Once associated with a persistent context, the persistent context is closed; or the object is serialized in another process. It has a persistent identifier. In most cases, there are corresponding rows in the database. For separated objects, Hibernate does not guarantee the correspondence between persistent identifiers and Java identifiers.

Iii. JMX Integration

JMX is the Jee standard for Java Component Management. Hibernate can be managed by the JMX service. In the release version, Hibernate provides an mbean implementation, org. hibernate. JMX. hibernateservice.

On JBoss, you can get the following benefits when using JMX:

1. session management

The lifecycle of a hibernate session can be automatically bound to the scope of a JTA transaction. This means that you do not need to manually open and close the session, which becomes the task to be completed by the JBoss EJB interceptor. In your code, you do not need to worry about Transaction Division, unless you want to write a lightweight persistence layer by using hibernate transaction APIs. You can call hibernatecontext to access the session.

2. Har deployment

Generally, the JBoss service deployment descriptor (in the ear or SAR file) is used to publish the hibernate JMX service. It supports all common configuration options of the hibernate sessionfactory. In any case, you also need to describe all the ing files in deployment descriptor. If you use the optional Har deployment, JBoss will automatically detect all the Har ing files in the Har file.

Iv. JCA support

Hibernate can also be configured as a connector. This is a practical feature.

The above four content groups are the first part of my hibernate document notes. For more information, see the other two sections.

Hibernate document notes are divided into three parts. The second part describes contextual sessions, configuration, and sessionfactory and JDBC connections (session is the encapsulation of JDBC connections ).

5. Contextual sessions

Many applications need a hibernate session associated with the context. Such a session is a session that is valid throughout the context of the given environment. In any case, the definition of the application context varies depending on the definition of the current concept.

Applications of previous versions of hibernate 3.0 tend to use their own threadlocal-based maintenance of the sessions between the front and back, such as the hibernateutil help class; or use a third-party framework (spring or Pico) based on proxy or interception mechanisms ).

From Hibernate 3.0.1, Hibernate adds the sessionfactory. getcurrentsession () method. Initially, it is assumed that the scope and context of the current session are defined using a JTA transaction. During the hibernate team's maintenance, the mature and excellent implementation of JTA transactionmanager is given. most (but not all) applications should make JTA transaction management, whether or not it is published to a Jee container. Based on this, JTA is required to maintain sessions in the context.

In any case, the processing after hibernate 3.1, sessionfactory. getcurrentsession () can be pluggable, that is, the range and context of the session can be used. The New Extended Interface (Org. hibernate. Context. currentsessioncontext) and the new configuration parameter (hibernate. current_session_context_class) are added to allow plugging, that is, the range and context of the session can be defined.

For more information, see org. hibernate. Context. currentsessioncontext. It defines a currentsession () method to track sessions associated with the current context. Hibernate provides three implementation methods for this interface.

1.org. hibernate. Context. jtasessioncontext

The current session is tracked and identified by JTA transactions. The processing process here is similar to that of the old JTA.

2.org. hibernate. Context. threadlocalsessioncontext

The current session is tracked by the thread currently being executed.

3.org. hibernate. Context. managedsessioncontext

The current session is tracked by the thread currently being executed. You are responsible for binding and unbinding the current session to the execution thread by using the static method of this class. This class does not open, flush, or close session.

The first two implementation classes provide the "One session corresponds to one database transaction" programming mode, which is also known as the "session-per-request" mode. The start and end of the hibernate session are based on the execution time of transactions in the database. If you use programming to divide transactions and use a simple JSE instead of a JTA, you should consider using the hibernate transaction APIs to hide the lower-layer transaction code. If you are using JTA, use the JTA interface to divide transactions. If you run a program in a container that supports CMT (container management transaction), the transaction is defined by declaration, and no code is required in your program to divide the transaction.

The hibernate. current_session_context_class parameter should be specified, which is an implementation class of org. hibernate. Context. currentsessioncontext. If the configuration parameter is not set, but an org. hibernate. transaction. transactionmanagerlookup is configured, Hibernate uses org. hibernate. Context. jtasessioncontext. Backward compatibility should be considered here. In typical cases, this parameter is the name of the class used. For the three implementation classes provided by hibernate, there are three brief names, "JTA", "Thread", and "managed ".

Vi. Configuration

1. Programming Configuration

An instance of org. hibernate. cfg. Configuration indicates the ing of all Java types of an application to the database type. Org. hibernate. cfg. configuration is used to build an org. hibernate. sessionfactory. The compiled ing comes from all XML ing files.

Part 1.

 
 
  1. Configuration cfg = new Configuration().addResource(“test.hbm.xml”); 

Segment 2.

 
 
  1. Configuration cfg = new Configuration().addClass(com.test.class); 

Segment 3.

 
 
  1. Configuration cfg = new Configuration().setProperty(“hibernate.dialect”, “org.hibernate.dialect.DB2Dialect”); 

Options that configuration can receive:

(1) pass a java. util. properties to configuration. setproperties ().

(2) place a hibernate. properties file to the root directory of the class path.

(3) set system properties through Java-dproperty = value.

(4) include the tag value in the hibernate. cfg. xml file.

The Org. hibernate. cfg. Configuration object is intentionally generated as a start time. Once sessionfactory is created, it will be discarded.

VII. Obtain sessionfactory

After org. hibernate. cfg. Configuration resolves all the ing files, the application should obtain the factory of an org. hibernate. Session instance. This factory is shared by all threads of the application.

 
 
  1. SessionFactory sessionFactory = cfg.buildSessionFactory(); 

Hibernate allows an application instance to have multiple sessionfactory instances. It is very useful for applications that use multiple databases.

8. JDBC connections (session is the encapsulation of JDBC connections)

Generally, you should use org. hibernate. sessionfactory to create or share JDBC. This method is very simple.

 
 
  1. Session session = sessionFactory.openSession(); 

When your operations need to access the database, a JDBC connection will be obtained from the connection pool.

For this work, we should provide some JDBC connection attributes for hibernate. All hibernate attribute names and semantics are defined in org. hibernate. cfg. environment. We now describe some more important settings for the JDBC connection configuration.

1. If you set the following attributes, Hibernate will get or share the connection using Java. SQL. drivermanager:

 
 
  1. hibernate.connection.driver_class  
  2.  
  3. hibernate.connection.url  
  4.  
  5. hibernate.connection.username  
  6.  
  7. hibernate.connection.password  
  8.  
  9. hibernate.connection.pool_size 

Hibernate's own connection pool algorithm has not developed. It is used for your initial contact, not for your product, or even for performance testing. For better performance and stability, you should use a third-party connection pool product. You only need to replace the settings of the hibernate. Connection. pool_size attribute with the corresponding connection pool settings. This will close the connection pool inside hibernate. For example, c3p0 can be used.

C3p0 is an open-source JDBC connection pool. It is stored in the lib directory of the hibernate release file and released along with hibernate. If you set the hibernate. c3p0. * attribute, Hibernate uses org. hibernate. Connection. c3p0connectionprovider as the shared connection. If you want to use proxool as the connection pool, you can view hibernat. properties or the hibernate site to obtain the attribute name settings you want to set.

C3p0 configuration example, attribute file segment:

 
 
  1. hibernate.connection.driver_class=  
  2.  
  3. hibernate.connection.url=  
  4.  
  5. hibernate.connection.username=  
  6.  
  7. hibernate.connection.password=  
  8.  
  9. hibernate.c3p0.min_size=  
  10.  
  11. hibernate.c3p0.max_size=  
  12.  
  13. hibernate.c3p0.timeout=  
  14.  
  15. hibernate.c3p0.max_statements=  
  16.  
  17. hibernate.dialect= 

2. For programs running on the application server, you should configure hibernate to find the server's javax. SQL. datasource through JNDI to obtain the connection. You need to set the following attributes.

 
 
  1. Hibernate. Connection. datasource
  2.  
  3. Hibernate. JNDI. URL (optional)
  4.  
  5. Hibernate. JNDI.Class(Optional)
  6.  
  7. Hibernate. Connection. username (optional)
  8.  
  9. Hibernate. Connection. Password (optional)

You can implement org. hibernate. Connection. connectionprovider to define your own connection acquisition policy. Use your own definition through hibernate. Connection. provider_class configuration.

 

The Hibernate document notes are divided into three parts. The third part focuses on optional configuration items, it includes hibernate configuration items, Hibernate JDBC and connection attributes, Hibernate cache attributes, Hibernate transaction attributes, and miscellaneous properties.

9. optional configuration items

The Hibernate attributes described below are system-level. System-level attributes can only be set through-dproperty = value or in the hibernate. properties file. The preceding settings are not supported.

1. hibernate configuration items

(1) After hibernate. dialect specifies a dialect, Hibernate can automatically generate optimized SQL statements based on the lower-layer database. The value is the inheritance class of org. hibenate. dialect. dialect. In most cases, Hibernate can determine based on the metadata returned by the lower-layer JDBC.

(2) hibernate. show_ SQL prints all SQL statements to the console. You can set the log policies of the org. hibernate. SQL class to debug level to achieve the same effect. Valid value: True | false.

(3) When hibernate. format_ SQL formatting SQL statements are printed on the console or written into log files. Valid value: True | false.

(4) When hibernate. default_schema generates an SQL statement, it adds the tablespace or database schema given by the ing file before the table name ). The value is Schema_name.

(5) When hibernate. default_catalog generates an SQL statement, add the catalog file before the table name. The value is catalog_name.

(6) After hibernate. session_factory_name hibernate creates the org. hibernate. sessionfactory instance, it will automatically bind the instance to the name in the JNDI. Set the value to JNDI/SF.

(7) hibernate. max_fetch_depth sets the maximum depth of external connections to a single table. 0 is used to block the default external connection settings. We recommend that you set it to 0 to 3.

(8) hibernate. default_batch_fetch_size sets the scale of the hibernate batch joint query. It is strongly recommended. Recommended values: 4, 8, and 16.

(9) hibernate. default_entity_mode default object expression mode. All sessions opened through sessionfactory. Value: Dynamic-map, dom4j, and pojo.

(10) hibernate. order_updates forces hibernate to sort SQL updates by the primary key value of the updated item. In this way, the transaction deadlock can be reduced in high concurrency. Valid value: True | false.

(11) If hibernate. generate_statistics is set to true, Hibernate will adjust the performance and collect statistics. Valid value: True | false.

(12) If hibernate. use_identifier_rollback is set to true, the generated identifier property will be reset to the default value. After the object is deleted. Valid value: True | false.

(13) If hibernate. use_ SQL _comments is set to true, hiberante generates comments for SQL, which is more conducive to debugging. The default value is false. Valid value: True | false.

2. hibernate JDBC and connection attributes

(1) hibernate. JDBC. fetch_size specifies the JDBC query scale. Call (statement. setfetchsize ()).

(2) hibernate. JDBC. batch_size specifies how hibernate uses jdbc2 for batch update. Value Range: 5 to 30.

(3) If hibernate. JDBC. batch_versioned_data sets this attribute to true, JDBC returns the correct number of rows after executebatch is executed. This parameter is usually safe. Hibernate automatically decodes the data using batch DML. The default value is false. Valid value: True | false.

(4) choose a custom org. hibernate. JDBC. batcher for hibernate. JDBC. factory_class. This attribute is not required for all applications. Value, which defines the Class Name of the factory.

(5) hibernate. JDBC. use_scrollable_resultset hibernate uses a rolling record set of jdbc2. You need to set this parameter when using the JDBC connection provided by the user. Otherwise, Hibernate connects to metadata. Valid value: True | false.

(6) When hibernate. JDBC. use_streams_for_binary reads or writes binary data or serializes data from JDBC or to JDBC, the stream is used. System-level data. Set true | false.

(7) after hibernate. JDBC. use_get_generated_keys is inserted, you can use the value in jdbc3 preparedstatement. getgeneratedkeys () to retrieve the locally generated key value. Jdbc3 + and jre1.4 + are required. If your driver has a problem after using hibernate identifier generator, set it to false. By default, you can connect to metadata. Valid value: True | false.

(8) hibernate. Connection. provider_class implements the Class Name of the org. hibernate. Connection. connectionprovider interface and provides a connection for hibernate.

(9) hibernate. Connection. Isolation sets the JDBC transaction isolation level. Check the constant value defined by Java. SQL. Connection. Note that most databases do not support all isolation levels, some additional and non-standard isolation levels. Optional values: 1, 2, 4, and 8.

(10) automatic submission of hibernate. Connection. autocommit JDBC shared connection. (Not recommended), true | false.

(11) hibernate. Connection. release_mode specifies when hibernate should release the JDBC connection. By default, JDBC always exists until the session is explicitly closed or disconnected. For the JTA data source on the application server, you should use after_statement to force release the JDBC connection after each JDBC request ends. For non-JTA data sources, it is usually meaningful to release the JDBC connection after each transaction ends. When this value is set to Auto, the after_statement mode is selected for JTA and CMT transaction policies. In the JDBC transaction policy, select after_transaction. Optional values: auto (default), on_close, after_statment, and after_transaction.

Note: This setting only affects sessions opened through sessionfactory. opensession. For sessions obtained through sessionfactory. getcurrentsession, The currentsessioncontext class configuration is used to control the connection release mode of these sessions.

(12) hibernate. Connection. Pass these attributes to drivermanager. getconnection.

(13) hibernate. JNDI. Pass these attributes to the JNDI initialcontextfactory.

3. hibernate cache attributes

(1) cacheprovider class name customized by hibernate. cache. provider_class.

(2) hibernate. cache. use_minimal_puts spend more read operations to optimize the minimum write operations for the second-level cache. This operation is very useful for cluster cache. In hibernate3, this function is enabled for cluster cache by default. Valid value: True | false.

(3) Enable query cache for hibernate. cache. use_query_cache. You must enable query cache for some queries. Valid value: True | false.

(4) hibernate. cache. use_second_level_cache may have been used to completely blocking the second-level cache. It is enabled by default, and the cacheprovider implementation class is specified. Valid value: True | false.

(5) The Class Name of the querycache interface implemented by hibernate. cache. query_cache_factory. The default value is the built-in standardquerycache.

(6) hibernate. cache. region_prefix uses the prefix of the second-level cache region name.

(7) hibernate. cache. use_structured_entries forces hibernate to use a more user-friendly format when storing data to the second-level cache. Valid value: True | false.

4. hibernate transaction attributes

(1) hibernate. transaction. transaction_class uses the Class Name of the transactionfactory of the hibernate transaction APIs. The default value is jdbctransactionfactory.

(2) JTA. usertransaction jtatransactionfactory uses the JNDI name to get JTA usertransaction from the application server. Valid value: JNDI/UT.

(3) hibernate. transaction. manager_lookup_class is the class name of the transactionmanagerlookup implementation class. This value is required when JVM-level cache is enabled or HiLo generator is used in the JTA environment.

(4) If hibernate. transaction. flush_before_completion is set to true, the session will automatically push the value of the cache area to the database before the Transaction Completes. Built-in and automatic session context management are preferred. Valid value: True | false.

(5) If hibernate. transaction. auto_close_session is set to true, the session will be automatically closed after the transaction is completed. Built-in and automatic session context management are preferred. Valid value: True | false.

5. Miscellaneous properties mixed attributes

(1) hibernate. current_session_context_class provides a policy for the current session lifecycle. Value: JTA, thread, managed, and custom class name.

(2) hibernate. query. factory_class: select the parsing implementation class of hsql. Valid values: org. hibernate. hsql. Ast. astquerytranslatorfactory and org. hibernate. hsql. Classic. classicquerytranslatorfactory.

(3) mappings between tags in hibernate. query. subsitutions Hibernate and those in SQL. For example, it can be a function name or a common string name. Optional values: hsqliteral = SQL _literal and hqlfunction = sqlfun.

(4) hibernate. hbm2ddl. Auto when sessionfactory is created, it automatically verifies or outputs the mode DDL (also the table creation statement) to the database. That is to say, the system automatically verifies the database table structure, deletes the table structure, and creates a new one, or updates the data table structure in the original table structure. When the value is set to create-drop, the table structure in the database will be deleted when sessionfactory is cleared. Values: validate, create, update, and create-drop.

(5) hibernate. cglib. use_reflection_optimizer uses cglib to replace the runtime reflection (System Level Attribute ). When there is a fault, reflection is very useful. Note that hibernate always requires cglib, even after you disable optimization. You cannot set this attribute in the hibernate. cfg. xml file.

Source: http://blog.163.com/swine_king/blog/static/8588207920104711273174/

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.