Hibernate (iii) structure-configuration file-entity mapping and configuration file

Source: Internet
Author: User

I. Architecture

  • Sessionfactory: A thread-safe, immutable cache snapshot of a compiled map file belonging to a single database. Session of the factory. It is possible to hold an optional data cache that can be stored at the process level or at the group level to reuse data in a transaction.
  • Sessions, session: Single-threaded, short-life objects that represent a conversation between the application and the persistence layer. Encapsulates a JDDBC connection, which is also a transaction factory that holds a cache of objects that must be persisted, used to traverse an object, or to find an object through an identifier.
  • Persistent objects (persistent object) and their collections (Collection): Short-life single-threaded objects that contain persistent state and commercial functionality. A flexible javabeans/pojos. (Plain old Java Objects, simple clean Java object) is sometimes also referred to as Plain ordinary Java Objects, which represents a collection of data. The only special thing is that they now belong to a session, and once the session is closed, they are all removed from the session and can be freely used at any program level such as: Directly as a DTO (i.e. data transfer object) to the presentation layer, data transfer object.
  • Temporary objects (Transient object) and their collections (Collection): There is currently no instance of a persisted class that belongs to a session. It may have just been instantiated by the program, has not had time to be persisted, or is instantiated by a closed session, temporary object.
  • Transaction, Transaction: (optional) A single-threaded, short-life object that the application uses to represent atomic operations of a batch of work. Is the abstraction of the underlying JDBC,JTA or CORBA transaction. JTA, Java Transaction API,JTA allows applications to perform distributed transactions-access and update data on two or more network computer resources. The JTA support of the JDBC driver greatly enhances the data access capability. CORBA (Common object request broker Architecture, public object Solicitation broker architecture, Common Object Request Broker architecture). A seesion may span multiple transaction transactions in some cases
  • ConnectionProvider: (optional) JDBC-connected factories and pools. Abstract from the underlying datesource or DriverManager. The corresponding program is not visible, but can be expanded and implemented by development.
  • Transactionfactory: (optional) The instance factory of the transaction. The application is not visible and can also be expanded and implemented by development.
Second, the configuration file-- -xml Format

Configuration file defaults to: Hibernate.cfg.xml

During hibernater initialization, the file is automatically found in the Classpath and the configuration information is read to prepare for subsequent database operations.

The configuration file should be deployed in Classpath, and for WEB applications, the configuration file should be placed in the \web-inf\classes directory

Configuration file Contents:

<?XML version= ' 1.0 ' encoding= ' UTF-8 '?><!DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hi Bernate.sourceforge.net/hibernate-configuration-3.0.dtd "><!--Generated by MyEclipse Hibernate Tools. -<hibernate-configuration>    <session-factory>        <!--dialect -        < Propertyname= "dialect">Org.hibernate.dialect.Oracle9Dialect</ Property>        <!--Database URL -        < Propertyname= "Connection.url">Jdbc:oracle:thin: @localhost: 1521:orcl</ Property>        <!--user name for database access -        < Propertyname= "Connection.username">Accp</ Property>        <!--password for the user name accessed by the database -        < Propertyname= "Connection.password">Accp</ Property>        <!--database driver Here is the Oracle database -        < Propertyname= "Connection.driver_class">Oracle.jdbc.OracleDriver</ Property>        < Propertyname= "Myeclipse.connection.profile">Oracle</ Property>        <!--whether to display the executed SQL statement -        < Propertyname= "Show_sql">True</ Property>        <!--whether to use an out -of-database connection -        < Propertyname= "Hibernate.use_outer_join">True</ Property>        <!--Transaction Management Type -        < Propertyname= "Hibernate.transaction.factory_class">net.sf.hibernate.transaction.JDBCTransactionFactory</ Property>        <!--Mapping File Configuration -        <MappingResource= "Com/pb/entity/login.hbm.xml" />    </session-factory></hibernate-configuration>
Third, Entity mapping

The object-relational mapping in Hibernate is to correspond the entity class to the table in the database, implementing the attributes in the entity class with the field one by one in the database table.

Mappings are created by the definition of a persisted class (entity Class), not the definition of a table.

Configuration files can be written manually, or they can be generated automatically by using tools such as: MyEclipse to generate entity classes

Configuration file Name: Class name. hbm.xml

<?XML version= ' 1.0 ' encoding= ' utf-8 '?> <!--This is not the same as the Hibernate.cfg.xml configuration file Note -<!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate Configuration DTD 3.0//en" "Http://hibernat E.sourceforge.net/hibernate-mapping-3.0.dtd "> <!--This is not the same as the Hibernate.cfg.xml configuration file Note -<hibernate-mapping> <!--the class name and the table name in the database correspond to which user -    <classname= "Com.pb.entity.Login"Table= "LOGIN"Schema= "ACCP">      <!--ID represents the primary key column list type represents the data type -        <!--properties in a class -        <IDname= "username"type= "Java.lang.String">         <!--which field or column name is in the table -            <columnname= "USERNAME"length= " the" />            <!--the way assigned is generated is generated by an external external program and must be specified before save () . -        <!--native by Hibernate according to the database used by the use of identity, Hilo, sequence one of the primary key generation mode, flexibility is strong. If the identity is supported, the identity is used and sequence is used if sequence is supported.  -            <Generatorclass= "Assigned" />        </ID>        <!--Password segment Settings -        <!--names and data types in a class -        < Propertyname= "Password"type= "Java.lang.String">        <!--the name of the field in the table, the length can not, is not null true is not NULL, FALSE is nullable -            <columnname= "PASSWORD"length= " the"Not-null= "true"/>        </ Property>        <!--If there are other properties, set the same way as password -    </class></hibernate-mapping>

Iv. Hibernate Optional Configuration 4.1, hibernate configuration Items

(1) After hibernate.dialect the specified dialect, hibernate can automatically generate optimized SQL based on the lower database. The inherited class with a value of org.hibenate.dialect.Dialect. In most cases, Hibernate

Can be judged based on the metadata returned by the low level JDBC.

(2) Hibernate.show_sql Print all the SQL statements to the console, you can achieve the same effect by setting the Org.hibernate.SQL class's log policy to the debug level. Value True|false.

(3) HIBERNATE.FORMAT_SQL formatted SQL statement when printing to the console or writing to a log file. Value True|false.

(4) Hibernate.default_schema when generating an SQL statement, precede the table name with the table space (tablespace) or database schema (schema) given by the mapping file. Value schema_name.

(5) Hibernate.default_catalog when generating the SQL statement, precede the table name with the catalog given by the mapping file. Value Catalog_name.

(6) Hibernate.session_factory_name hibernate automatically binds this to the name in Jndi after the Org.hibernate.SessionFactory instance is created. Value JNDI/SF.

(7) Hibernate.max_fetch_depth sets the maximum depth of the number of outer joins to a single table. 0 is to mask the default external connection settings. The recommended setting is between 0 and 3.

(8) Hibernate.default_batch_fetch_size set the scale of Hibernate batch union query. Strongly recommended. Recommended settings are 4, 8, 16.

(9) Hibernate.default_entity_mode The default entity representation mode, open all sessions via sessionfactory. Values, Dynamic-map, dom4j, Pojo.

(hibernate.order_updates) Forced Hibernate to sort SQL updates by the primary key value of the item being updated. This can reduce transaction deadlock when high concurrency occurs. Value True|false.

(one) Hibernate.generate_statistics if set to True,hibernate, the statistics will be collected for performance tuning. Value True|false.

(Hibernate.use_identifier_rollback) If set to true, the resulting identity property will be reset to the default value when the object is deleted. The value is True|false.

Hibernate.use_sql_comments if set to True,hiberante will generate comments for SQL, which is more conducive to debugging. The default value is False. The value is True|false.

4.2. Hibernate JDBC and the properties of the connection

(1) hibernate.jdbc.fetch_size Specifies the query scale for JDBC. by calling (Statement.setfetchsize ()).
(2) hibernate.jdbc.batch_size specifies how Hibernate uses JDBC2 batch updates. Value, 5 to 30 is recommended.
(3) Hibernate.jdbc.batch_versioned_data Setting this property to TRUE,JDBC will return the correct number of rows after ExecuteBatch execution. This parameter is usually safe to open. Hibernate will automatically
the decoding of these data uses bulk DML. The default is False. Value True|false.
(4) hibernate.jdbc.factory_class Select a custom Org.hibernate.jdbc.Batcher. All applications do not need to configure this property. Value that defines the class name of the factory.
(5) Hibernate.jdbc.use_scrollable_resultset hibernate uses JDBC2 's scrollable recordset. This parameter needs to be set when using a user-supplied JDBC connection. Otherwise, Hibernate uses a connection
Connect metadata. Value True|false.
(6) Hibernate.jdbc.use_streams_for_binary when reading or writing binary data or serializing data from JDBC or to JDBC, use the stream. System-level data. Set the True|false.
(7) Hibernate.jdbc.use_get_generated_keys after insertion, you can use the value in JDBC3 's Preparedstatement.getgeneratedkeys () to retrieve the locally generated key value. Requires jdbc3+ and
jre1.4+ If you have a problem with your driver after using Hibernate identifier generator, set it to false. By default, you try to connect to metadata to decide. Value, True|false.
(8) Hibernate.connection.provider_class implements: The name of the class of the Org.hibernate.connection.ConnectionProvider interface, for hibernate Provides a connection.
(9) Hibernate.connection.isolation sets the level of JDBC transaction isolation. Check the defined constant values of the java.sql.Connection, but be aware that most databases do not support all isolation levels, some additional, and non-standard isolation levels. Value, 1, 2, 4, 8.
(Hibernate.connection.autocommit) automatic submission of JDBC shared connections. (not recommended) value, True|false.
(one) hibernate.connection.release_mode specifies when hibernate should release the JDBC connection. By default, JDBC is always present, only until the session is explicitly closed or disconnected
The next time. For the application's server JTA data source, you should use after_statement to force the release of the JDBC connection after each JDBC request ends. For non-JTA data sources, it is usually released after the end of each transaction
The JDBC connection is meaningful. When you set this value to auto, the JTA and CMT transaction policies are selected as After_statement mode. When a JDBC transaction policy is selected, After_transaction is chosen. Value, auto (default),
on_close,after_statment,after_transaction. Note: This setting affects only the session opened through Sessionfactory.opensession. For pass
The configuration of the Session,currentsessioncontext implementation class obtained by sessionfactory.getcurrentsession is used to control the connection release mode of these sessions.
hibernate.connection. Pass these properties to drivermanager.getconnection.
Hibernate.jndi. Pass these properties to the Jndi initialcontextfactory.

4.3. Hibernate Cache Property

(1) Hibernate.cache.provider_class Custom Cacheprovider class name.
(2) Hibernate.cache.use_minimal_puts spends more read operations to optimize the minimum write operation for level two cache. This operation is very useful for cluster caching. In Hibernate3, for cluster slow
This feature is turned on by default. Value, True|false.
(3) Hibernate.cache.use_query_cache Open the query cache, individual queries should definitely turn on the query cache. Value, True|false.
(4) Hibernate.cache.use_second_level_cache may have used to completely block out the level two cache, which is turned on by default, for the specified Cacheprovider implementation class. Value, True|false.
(5) Hibernate.cache.query_cache_factory implements the class name of the Querycache interface, which is built-in by default Standardquerycache

(6) Hibernate.cache.region_prefix prefix for using a two-level cache domain name.
(7) Hibernate.cache.use_structured_entries forced Hibernate to use a more user-friendly format when storing data to a level two cache. Value, True|false.

4.4.Hibernate Transaction Properties

(1) Hibernate.transaction.transaction_class the class name of the Transactionfactory using Hibernate transaction APIs. The default is Jdbctransactionfactory.

(2) Jta. UserTransaction Jtatransactionfactory uses jndi names to get JTA usertransaction from the application server. Value, Jndi/ut.

(3) Hibernate.transaction.manager_lookup_class is the class name of a Transactionmanagerlookup implementation class. This value is required when a JVM-level cache is turned on or when Hilo Generator is used in a JTA environment.

(4) Hibernate.transaction.flush_before_completion if set to True,session, the value of the buffer will be pushed into the database automatically before the transaction completion phase. Built-in and automatic session context management is preferred. Value, True|false.

(5) Hibernate.transaction.auto_close_session if set to True,session will automatically close the session after the transaction is completed. Built-in and automatic session context management is preferred. Take

Value, True|false.

4.5, miscellaneous properties of various mixed attributes

(1) Hibernate.current_session_context_class provides a strategy for the current session life cycle. Value, JTA, thread, managed, custom class name.

(2) Hibernate.query.factory_class Select the Analytic implementation class of Hsql. Values, Org.hibernate.hsql.ast.ASTQueryTranslatorFactory and

Org.hibernate.hsql.classic.ClassicQueryTranslatorFactory.

(3) Hibernate.query.subsitutions hibernate in the marker-to-SQL marker mapping. For example, it can be a function name or a normal string name. Values, such as hsqliteral=sql_literal,

Hqlfunction=sqlfun.

(4) Hibernate.hbm2ddl.auto when Sessionfactory is created, automatic validation or output mode DDL (also build table statements) into the database. That is, the automatic validation of the database table structure or the first deletion

In addition to re-establishing, or updating the data table structure on the original table structure. When the value is set to Create-drop, when Sessionfactory is cleared, the table structure in the database is deleted. Value, validate, create, update,

Create-drop.

(5) Hibernate.cglib.use_reflection_optimizer uses cglib instead of reflection (System-level attributes) for the run-time. In the case of faults, reflection is very useful, note that hibernate always needs cglib,

Even after you turn off optimization. You can not set this property in the Hibernate.cfg.xml file.

Hibernate (three) structure-profiles-entity mappings and configuration files

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.