Hibernate Reference Manual (Chapter 2)

zhaozj2021-02-08  253

Hibernate reference manual

Chapter 2 SessionFactory configuration

2.1 System configuration

The instance of the Net.sf.hibernate.Configuration object describes a complete collection of the Java type of the application to the relational database type. These mappings are compiled from a wide variety of XML mapping files. You can get an instance of the Configuration object by directing an instance. There is an example of establishing a data store from the map defined by the two XML configuration files:

Configuration CFG = New Configuration ()

.addfile ("Vertex.hbm.xml")

.addfile ("Edge.hbm.xml");

Another alternative method (better?) Is to let Hibernate use getResourceceAsStream () to load mapping files.

Configuration CFG = New Configuration ()

.addclass (eg.vertex.class)

.addclass (eg.edge.class);

After calling, Hibernate will automatically look for a mapping file that is named /eg/vertex.hbm.xml and /eg/edge.hbm.xml and /eg/edge.hbm.xml in ClassPath. This method eliminates all hard-coded file names.

System configuration can also specify several optional parameters.

Properties PROPS = New Properties ();

......

Configuration CFG = New Configuration ()

.addclass (eg.vertex.class)

.addclass (eg.edge.class)

.SETPROPERTIES (PROPS);

Configuration is designed as a "configuration process" object. Once the sessionFactory is established, the configuration object will be discarded.

2.2 Get sessionFactory

When all mappings are parsed by Configuration, the application must obtain a session factory for a session instance. This plant is designed to be shared by all application threads. However, Hibernate also allows your application to instantiate multiple SessionFactory, which will be very useful when you use multiple databases.

SESSIONFACTORY sessions = cfg.buildsessionFactory ();

2.3 Users provide JDBC connections

SessionFactory opens a session on the JDBC provided by the user. This design enables the application to freely select its desirable JDBC connection. The application must be noted that two concurrent sessions cannot be opened on the same connection.

Java.sql.connection conn = DataSource.getConnection ();

Session sess = sessions.opensions (conn);

// Start a new transaction (optional)

Transaction tx = sess.begintransaction ();

The last row is hereby optional - the application can choose to directly use the JTA or JDBC transactions to manage transactions. However, if you use the Hibernate transaction, your client code is abstract from the underlying implementation. (For example: You can switch to the CORBA transaction service in the future, without changing application code)

2.4 Hibernate provides JDBC connection

Another choice, you can use SessionFactory to open the database connection, but the premise is that the connection properties must be provided in the following method:

l Pass a java.util.properties instance to configure.SetProperties ()

l Place the hibernate.properties file in the root directory of ClassPath, l Use Java -Dproperty = Value to set the system properties.

l In the hibernate.cfg.xml file, contain element (see below)

If you set the following properties, Hibernate will use java.sql.drivermager to get the connection (or connect pool):

Hibernate.Connection.driver_class = JDBC Driver Class

Hibernate.Connection.url = JDBC URL

Hibernate.connection.userName = Database User

Hibernate.Connection.password = user password

Hibernate.connection.pool_size = maximum number of pooled connections

Hibernate.Statement_cache.size = maximum number of cached prepaaredStatements (Must Be 0 for Interbase)

Hibernate.connection.ission = Transaction Isolation Level (Optional)

Hibernate.Connection.xxxx = pass the jdbc property xxxx to drivermanager.getConnection ()

Hibernate.Connection.ilation must specify an integer value. (Check the Java.sql.connection to get the interpretation of this value, but most databases do not support all isolation levels)

Any connection properties can be passed by defining attribute names prefixed for "hibernate.connection". For example, you can specify a charset property via hibernate.connnection.charset.

Hibernate's own connection pool algorithm is not developed. C3P0 is an open source JDBC connection pool, which is posted with Hibernate in the lib directory. If you set the following properties, Hibernate will use C3P0 to provide the connection pool function:

Hibernate.c3p0.max_size = maximum connection pool size

Hibernate.c3p0.min_size = minimum connection pool size

Hibernate.c3p0.timeout = maximum idle time

Hibernate.c3p0.max_statements = Size of Statement Cache

However, in addition to the above settings, you still need to set hibernate.connection.driver_class, hibernate.connection.username, and hibernate.connection.password properties.

Hibernate also has built-in supporting Apache DBCP connecting pools. You need to enable DBCPConnectionProvider by setting hibernate.dbcp. * Property (DBCP connection pool properties) and hibernate.dbcp.ps. * (DBCP statement buffer properties). Please refer to Apache Commons-Pool documents to get a detailed description of these properties. All hibernate attribute names are defined in the net.sf.hibernate.Environment class. If the user uses a built-in application server, Hibernate can also get database connections by registering Javax.sql.DataSource in JNDI. Set the following properties:

Hibernate.Connection.DataSource = DataSource JNDI Name

Hibernate.jndi.url = url of the jndi provider (optional)

Hibernate.jndi.class = Class of the JNDI InitialContextFactory (Optional)

Hibernate.jndi.xxxx = pass the property xxxx to the jndi initialcontextfactory (optional)

Hibernate.connection.userName = Database User

Hibernate.Connection.password = user password

Then, simply open the session as just below:

Session sess = sessions.opensession (); // Obtain a JDBC Connection and

// instantiate a new session

// Start a new transaction (optional)

Transaction tx = sess.begintransaction ();

2.5 Other properties

There are also some optional other properties:

Attribute name

Attribute value

Description

Hibernate.Diact

Full.classname.of.diafor

Classname of a hibernate Diaforct - Enables CERTAIN Platform Dependent Features

Hibernate.default_schema

Schema_name

Qualify UNQualified Tablenames with the given schema / tablespace in generated SQL

Hibernate.Session_Factory_Name Jndi / Composite / Name Bind this name to the sessionFactory

Hibernate.use_outer_join

True | False

Enables outrijin fetching

Hibernate.jdbc.Fetch_size

A non-Zero Value

DETERMINES THE JDBC FETCH SIZE (Calls Statement.SetFetchSize ())

Hibernate.jdbc.batch_size

Recommended Values ​​Between 5 and 30 a Nonzero Value

Enables use of jdbc2 batCh Updates by Hibernate

Hibernate.jdbc.use_scrollable_Resultset

True | False

enables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user supplied connections. Hibernate uses connection metadata otherwise.hibernate.jdbc.use_streams_for_binary

True | False

Use streams when writing / reading binary or serializable types to / from jdbc

Hibernate.Connection.Provider_class

Full.classname.of.ConnectionProvider

ClassName of a Custom ConnectionProvider

Hibernate.Transaction.Factory_Class

Full.classname.of.transactionFactory

Classname of a TransactionFactory To Use with Hibernate Transaction API

JTA.USERTRANSACTION

NDI / Composite / Name

A jndi name buy by jtatransactionfactory to Obtain the JTA Utertrance

Hibernate.Transaction.Manager_lookup_class

Full.classname.of.transactionManagerLookup

Classname of a TransactionManagerLookup - Needed WHEN JVM-Level Caching Is Enabled in a JTA ENVIRONMENT

hibernate.query.imports package.name, other.package.name A list of packages containing persistent classes. If the package is listed here, your Hibernate queries need not specify the full class name of a persistent class. (You can use from foo in class foo as an alternative to from foo in class eg.foo.Foo.) hibernate.query.substitutions hqlLiteral = SQL_LITERAL, hqlFunction = SQLFUNC mapping from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names, for example ) hibernate.show_sql true | false Write All Sql Statements to Console (as an alternative to use of the logging functionality)

You should always set the hibernate.diaforct property to the correct net.sf.hibernate.Dialect.DiaLect subclass for your database. Unless you want to use Native or Sequence to generate primary keys or pessimism (session.lock (), session.loadwithlock (), these settings basically do not need to be strict. However, if you specify DiaLect, Hibernate will intelligently use the default settings of the above properties. Save the result of your manual settings. The following table lists the optional values ​​of the hibernate.diaforct property:

DB2 net.sf.hib2diact.db2DiaLECT

MySQL Net.sf.Hibernate.Dialev.MysqldiaAlact

SAP DB NET.SF.HIBERNATE.DIALECT.SAPDBDIALECT

Oracle Net.Sf.Hibernate.Dialev.OraclediaLect

Sybase net.sf.hibaRnate.DiaAlaforct.sybasediaLect

Progress Net.sf.hibResSDiaLect.ProgressDiaLect

McKoi SQL Net.sf.Hibernate.dialect.mckoidiaLect

Interbase net.sf.hibernate.dialev.InterbasediaLect

PointBase Net.sf.Hibernate.Dialev.PointBaseDiaALect

Postgresql net.sf.hibernate.diaalect.postgresqldiaLect

Hypersonicsql net.sf.hibernate.diaalect.hsqldiaalect

Microsoft SQL Server Net.sf.Hibernate.dialect.sybasediaLect

If your database supports an external connection of an ANSI or Oracle type, it will improve the performance of the external connection acquisition result by limiting the number of data round trips between the database (this is a database execution more work). The result of using external connections allows for multi-to-one-pair of object charts to be obtained in a single selection query. The obtained chart ends when the object change page, the object agent, or the loop reference. (The Fetched Graph Ends At Leaf Objects, Objects with Proxies Or Where Circular References Occur). This particular association behavior can be disabled by setting the Outer-Join property to false.

Oracle limits the size of the byte array passed between the database and the JDBC driver. If you want to use a large binary or last type, you should start the property hibernate.jdbc.use_streams_for_binary. And it is just a JVM level setting.

Hibernate.show_sql Property Force Hibernate Displays the SQL statement on the console. This approach provides a simple choice for enabling logs.

You can define a plugin that gets a JDBC connection policy by implementing interface net.sf.hibernate.connection.connectionProvider. You can set the hibernate.connection.provider_class property to set the custom implementation.

If you want to use the Hibernates transaction programming interface, you need to specify the factory class for transaction instance by setting hibernate.transaction.factory_class properties. There are two standards (built) options:

Net.sf.hibernate.Transaction.jdbcTransActionFactory delegated to JDBC transactions

Net.sf.hibernate.Transaction.jtatransActionFactory delegated to JTA (if there is a transaction is being executed, the session will perform tasks in his context, otherwise you will start a new transaction) You can also customize your transaction.

If you want to use the volatile data cache (JVM level) in the JTA environment, you must specify the policy of obtaining JTA TransactionManager.

Net.sf.hibernate.Transaction.JbosstransactionManagerLookup for jboss

Net.sf.hibernate.Transaction.WeblogictractionsManagerLookup for WebLogic

Net.sf.hibernate.Transaction.WebsphereTransactionManagerLookup for WebSphere

Net.sf.hibernate.Transaction.orionTransactionManagerLookup for Orion

Net.sf.hibernate.Transaction.resintransActionManagerLookup for Resin

If you want to bind SessionFactory to JNDI's namespace, you can use the property hibernate.session_factory_name and specify a name (such as: hibernate / session_factory). Example: In the future, EJBS can get sessionFactory by looking up JNDI. Hibernate will create an initial context environment using hibernate.jndi.url, hibernate.jndi.class properties.

Users can define new Hibernate query symbols using the hibernate.query.substitude. Properties. E.g:

Hibernate.query.substitude.x = 1, FALSE = 0

This translates "true" and "flash" symbols into a tincture when generating a SQL statement.

Hibernate.query.substitude.Substitude.QUWERCASE = LOWER

This sentence will rename the LOWER function in the SQL statement.

2.6 XML configuration file

There is also a configuration method that sets all configuration information in the file hibernate.cfg.xml. This file must be placed in the root directory of ClassPath.

"- // Hibernate / Hibernate Configuration DTD // EN"

"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

My / First / Datasource

net.sf.hibernate.diaalect.mysqldiaalect false

True

Java: Comp / Usertractions /

Hibernate can be configured simply as follows:

SessionFactory sf = new configuration ()

.configure ()

.BUILDSessionFactory ();

2.7 log

Hibernate records various events using apache commit-logging. The Commons-Logging log service will be output directly to the Apache log4 (if you place log4j.jar in classpath) or JDK1.4 logging (if you run on JDK1.4 or above). You can download LOG4J on http://jakarta.apache.org. To use log4j, you need to place the log4j.properties file in the directory of the classpath. An example of an attribute file is posted along with Hibernate.

to be continued……

转载请注明原文地址:https://www.9cbs.com/read-1202.html

New Post(0)