Hibernate usage Summary

Source: Internet
Author: User

There are three considerations for hibernate applications in Java::
1. Hibernate. properties can be directly built using hibernate, which contains the configuration templates required to connect to various types of databases.
2The ing between Hibernate and database tables can be achieved in two ways:
1> You must manually create a configuration file for the bean that is mapped to the database table and name it bean_name.hbm.xml.
2> by writing hibernate annotations required to establish database ing in these beans, XDoclet directly generates a configuration file for these beans
3. Lazy Loading)
When the query records are stored in a list through hibernate, if the data in the list is taken out before the session is closed, everything is normal; if the data in the list is taken out after the session is closed, the following error message is returned: lazyinitializationexception: cocould not initialize proxy-the owning session was closed.
I tried the hibernate. initialize (list) method (delayed loading can be achieved by force loading associated objects) and forcibly loaded the list directly, but there is still a problem. The current solution is to avoid retrieving data from the stored object after closing the session.

Hibernate supports four types of connection pools(The downloaded jarpackage is included in the hibernate.zip Package). The details are as follows:
1> built-in hibernate:
# Hibernate. Connection. pool_size the maximum number of connection pool capacity (only this configuration is available)
2> c3p0
# Hibernate. c3p0. max_size 2 Maximum number of connections
# Hibernate. c3p0. min_size 2
# Hibernate. c3p0. Timeout 5000 maximum holding time of database connection objects (in seconds)
# Hibernate. c3p0. max_statements 100 maximum cacheable database statement object. If it is set to 0, it is not cached.
# Hibernate. c3p0. ID le_test_period 3000
# Hibernate. c3p0. acquire_increment 2
# Hibernate. c3p0. Validate false
3> proxool
# Hibernate. proxool. pool_alias pool1
##=== Only need one of the following ====
# Hibernate. proxool. existing_pool true
# Hibernate. proxool. xml proxool. xml
# Hibernate. proxool. properties proxool. Properties
4> DBCP
# Hibernate. DBCP. maxactive maximum number of valid database connections
# Hibernate. DBCP. maxidle maximum number of idle database connections
# Hibernate. DBCP. maxwait database connection maximum idle time (in milliseconds, set to-1 to close)
# Hibernate. DBCP. whenexhaustedaction: the countermeasure when the connection pool is exhausted. If it is 0, it will not respond. If it is 1, it will be blocked until there is an available connection. If it is 2, a new connection will be added.
# Hibernate. DBCP. testonborrow: checks whether the connection is valid when the connection pool obtains the connection.
# Hibernate. DBCP. testonreturn check whether the connection is valid when the connection pool is returned

The following sections describe in detail when using hibernate (the configuration file is generated through XDoclet):

First, the bean that establishes a ing relationship with the database table

Package com. Neu. Bean;

// When the dynamic-update setting is used to generate an update SQL statement, it only contains the currently changed fields.
// When dynamic-inser is set to generate insert SQL, only the current non-empty field is included.

/**
* @ Hibernate. Class
* Table = "user_info"
* Dynamic-insert = "true"
* Dynamic-update = "true"
*
*/

Public class userinfo {
Private int ID;
Private string name;
Public userinfo (){
This. ID = 0;
This. Name = "";
}

// Hibernate. ID is used to describe the ing between the key fields in pojo (plain ordinary Java object) and the primary keys in the database table.
// Generator-class sets the primary key generation mode
// Set the primary key field name for Column

/**
* @ Hibernate. ID
* Generator-class = "assigned"
* Type = "int"
* Column = "ID"
*/
 
Public int GETID (){
Return ID;
}
Public void setid (int id ){
This. ID = ID;
}

// Hibernate. Property is used to describe the ing between attributes in pojo and database table fields.
// Set the field name of the database table in Column

/**
* @ Hibernate. Property
* Column = "name"
*/
Public String getname (){
Return name;
}

Public void setname (string name ){
This. Name = Name;
}
}

Next, perform database operations:

// Use the initialization code of the bean_name.hbm.xml configuration file
Configuration Config = new configuration (). addclass (userinfo. Class );
Sessionfactory sessions = config. buildsessionfactory ();
New schemaexport (config). Create (True, true); // create the database table (two attributes: whether to print the script on the console and whether to export the script)
Session session = sessions. opensession (); // session is the basis for persistent layer operations, which is equivalent to connection in JDBC
// Insert record operation
Userinfo user = new userinfo ();
User. setid (1 );
User. setname ("Nokia ");
Session. Save (User );
Session. Flush ();
// Query and update records
Query q = session. createquery ("from userinfo where name = 'nokia '"); // userinfo indicates the bean name, not the database table name.
List list = (list) Q. List ();
User = (userinfo) Q. List (). Get (0 );
User. setname ("neu ");
Session. Update (User );
Session. Flush (); // force the user instance to be synchronized to the database immediately. When the other session is closed, the flush method is automatically executed.
Session. Close ();

Then, let's take a look at the detailed configuration of build. xml.

<! -- Use the following code to generate a. HBM. xml configuration file based on the bean that establishes a ing relationship with the database table -->
<Target name = "init" depends = "Todo">
<Javac srcdir = "$ {SRC}" destdir = "$ {class}" classpathref = "path. Lib. hibernate" DEBUG = "on"/>
<Taskdef name = "hibernatedoclet"
Classname = "XDoclet. modules. hibernate. hibernatedoclettask"
Classpathref = "path. Lib. XDoclet"/>
<Hibernatedoclet destdir = "$ {conf}">
<Fileset dir = "$ {SRC}">
<Include name = "**/*. Java"/>
</Fileset>
<Hibernate version = "3.0"/>
</Hibernatedoclet>
</Target>

<! -- The following code can be used to generate. HBM. create a database table in the XML file (if the table already exists, drop the table first) and generate the corresponding SQL script file -->
<Target name = "createhiber" depends = "init">
<! -- Schemaexport is the schema generator, which can generate a ing file from compiled Java classes or Java source code with the XDoclet mark -->
<Taskdef name = "schemaexport" classname = "org. hibernate. tool. hbm2ddl. schemaexporttask" classpathref = "path. Lib. All"/>
<! -- Properties: reads database attributes from a specified file
Does quiet output SQL scripts?
Whether to run text in the database
Whether to perform the drop tables operation
Delimiter sets the row Terminator for the script
Output saves the output script to the specified file -->
<Schemaexport properties = "$ {conf}/hibernate. properties "quiet =" no "text =" no "Drop =" no "delimiter ="; "output =" $ {conf}/schema-export. SQL ">
<! -- The generated HBM. xml configuration file must be put together with the corresponding class file -->
<Fileset dir = "$ {class}">
<Include name = "**/*. HBM. xml"/>
</Fileset>
</Schemaexport>
</Target>

Note: 1. Build the program once before running it to generate the HBM. xml configuration file required for running the program.
2. Copy the hibernate. properties file to the root directory of classes so that the file can be found only when the program is running.

Reference: http://www.stallian.com/docs/java/hibernate/2.1/overview-tree.html

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.