Hibernate in-depth understanding of----02HelloWorld (Hibernate.cfg.xml configuration file, creating persistent objects in a detailed)

Source: Internet
Author: User
Tags bulk insert commit constructor current time flush access database oracle database

Reference code Download GITHUB:HTTPS://GITHUB.COM/CHANGWENSIR/JAVA-EE/TREE/MASTER/HIBERNATE4


1. Create a Hibernate.cfg.xml configuration file

<?xml version= ' 1.0 ' encoding= ' utf-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration dtd//en" "Http://www.hibernat  E.org/dtd/hibernate-configuration-3.0.dtd ">  

Hbm2ddl.auto: This property helps programmers to implement forward engineering, that is, to generate database scripts from Java code, resulting in a concrete table structure. 。 Value Create | Update | Create-drop | Validate
-Create: The data table will be generated according to the. hbm.xml file, but each run will delete the last table and regenerate the table, even if two times without any change
-Create-drop: The table is generated according to the. hbm.xml file, but the table is automatically deleted when the sessionfactory is closed
-Update: The most commonly used attribute values will also generate tables based on the. hbm.xml file, but if the. hbm.xml file and the table structure of the corresponding data table in the database are different, Hiberante will update the data table structure, but will not delete the existing rows and columns
-Validate: Compares the tables in the database and throws an exception if the columns in the. hbm.xml file do not exist in the data table
Format_sql: Whether to convert SQL to well-formed SQL. Value TRUE | False
1-1.hibernate configuration fileHibernate profiles are primarily used to configure the various properties required by the database connection and Hibernate runtime
Each Hibernate configuration file corresponds to a configuration object
Hibernate configuration files can be in two formats:
-Hibernate.properties (not recommended)
-Hibernate.cfg.xml
Common Properties of Hibernate.cfg.xml
1). JDBC Connection Properties

-Connection.url: Database URL
-Connection.username: Database user name
-Connection.password: Database user password
-Connection.driver_class: Database JDBC Driver
-dialect: The dialect of the configuration database, which produces different SQL statements depending on the underlying database, Hibernate optimizes access for database features

2). C3P0 database Connection Pool Properties
-Hibernate.c3p0.max_size: Maximum number of connections to the database connection pool
-Hibernate.c3p0.min_size: Minimum number of connections to the database connection pool
-Hibernate.c3p0.timeout: The Connection object in the database connection pool should be destroyed when it has not been used for a long time
-hibernate.c3p0.max_statements: Number of cached Statement objects
-Hibernate.c3p0.idle_test_period: Indicates how long the connection pool detection thread is detecting whether all linked objects in the pool have timed out. The connection pool itself does not remove itself from the connection pool, but rather a thread that does it at certain intervals by comparing the last time the connection object was used and the current time to timeout, and then deciding whether to destroy the connection object.
-Hibernate.c3p0.acquire_increment: How many database connections are acquired at the same time when a connection in the database connection pool is exhausted

-Show_sql: Whether to output the SQL generated by the run-time to the log for debugging. Value TRUE | False
-Format_sql: Whether to convert SQL to well-formed SQL. Value TRUE | False
-Hbm2ddl.auto: Automatically create, update, or delete database schemas when starting and stopping. Value Create | Update | Create-drop | Validate
-Hibernate.jdbc.fetch_size
-Hibernate.jdbc.batch_size

3). Jdbc.fetch_size and Jdbc.batch_size
Hibernate.jdbc.fetch_size: Essentially, call the Statement.setfetchsize () method to set the number of records fetched from the database each time the JDBC Statement reads the data.
-for example, query 10,000 records at a time, for the JDBC driver of Oracle, it is not 1 times to take 10,000 strip out, but only take out the fetchsize number, when the result set traversed these records, then go to the database to fetch fetchsize bar data. Therefore, the unnecessary memory consumption is greatly saved. Fetch size Sets the larger the number of times the database is read, and the faster the fetch size, the more times the database is read, the slower the speed. The default fetch Size = 10 for the JDBC drive of the Oracle database is a conservative setting that, depending on the test, will increase performance by 1 time times when fetch size=50, and fetchsize=100 performance can continue to increase when the 20%,fetch Size continues to grow, and the performance gains are not significant. Not all databases support the fetch size feature, such as MySQL does not support

Hibernate.jdbc.batch_size: Sets the batch size for bulk Delete, batch update and BULK INSERT, similar to the meaning of setting buffer size. The larger the batchsize, the lower the number of times a batch operation sends SQL to the database, the faster it becomes.
-The test result is that when batch size=0, it takes 25 seconds to delete 10,000 records from the Oracle database using Hibernate, and Batch Size = 50, it takes only 5 seconds to delete. Oracle Database batchsize=30 is the right time.
2. Creating Persistent Objects

public class News {
    private Integer ID;
    Private String title;
    Private String author;
    Private Date occurrencedate;

    Public News (string title, string author, Date occurrencedate) {
        super ();
        this.title = title;
        This.author = author;
        This.occurrencedate = occurrencedate;
    }

    Public News () {
    }
//Omit Get,set method
}

To create a persisted Java class
-Provides an argument-free constructor: Enables hibernate to instantiate a persisted class using Constructor.newinstance ()
-Provides an identity attribute (identifier property): typically mapped to a primary key field of a database table. Without this attribute, some features will not work, such as: Session.saveorupdate ()
Declaring an access method for a class's Persisted class field (Get/set): Hibernate persists for JavaBeans-style attributes.
-Using non-final classes: generating agents at run time is an important feature of Hibernate. If the persisted class does not implement any interfaces, Hibnernate uses the CGLIB build agent. If you are using the final class, you cannot generate the CGLIB proxy.
-Overriding the Eqauls and Hashcode methods: If you need to put an instance of a persisted class into the Set (when you need to do the correlation mapping), you should override both methods

Hibernate does not require a persisted class to inherit any parent class or implement an interface, which ensures that the code is not contaminated. That's why hibernate is called low-intrusive design.
Hibernate uses XML-formatted files to specify mappings between objects and relational data. Hibernate will generate various SQL statements based on this mapping file at run time
The map file has the extension. hbm.xml
3. Creating objects--mapping files

Once created, this file needs to be configured in Hibernate.cfg.xml

<?xml version= "1.0"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/

    Hibernate-mapping-3.0.dtd ">  
4. Test Access database

The following tests are based on this, please note that

    Private Sessionfactory sessionfactory;
    Private session session;

    Private Transaction Transaction; @Before public void init () {//Create a Configuration object: Basic configuration information and object relationship mapping information for utils Configura

        tion = new Configuration (). Configure ();
        Create a Serviceregistry object: Utils 4.x any configuration and services that are newly added to the object//utils need to be registered in the object before they are valid. Serviceregistry serviceregistry = new Serviceregistrybuilder (). Applysettings (Configuration.getproperties ()

        ). Buildserviceregistry ();

        Sessionfactory = Configuration.buildsessionfactory (serviceregistry);

        Create a Session Object session = Sessionfactory.opensession ();
    Open transaction Transaction = Session.begintransaction ();

        } @After public void Destroy () {//COMMIT TRANSACTION: The statement transaction.commit () that actually interacts with the database;

        Close Session session.close ();
    Close Sessionfactory object Sessionfactory.close (); } <pre NAme= "Code" class= "Java" > @Test public void Test () {}

 

If you create the table successfully, complete this instance
4-1.configuration class

The configuration class is responsible for managing Hibernate config information. Include the following:
-Hibernate runs the underlying information: database URL, user name, password, JDBC driver class, database dialect, database connection pool, etc. (corresponding to Hibernate.cfg.xml file).
-Persistence class and data table mapping (*.hbm.xml file)
Two ways to create a Configuration
-Properties file (Hibernate. Properties):
· Configuration cfg = new configuration ();
-XML file (hibernate.cfg. XML)
· Configuration cfg = new configuration (). Configure ();
-The Configure method of the Configuration also supports access with parameters:
· File File = new file ("Simpleit.xml");
· Configuration cfg = new configuration (). Configure (file);
4-2.sessionfactory Interface

 -A compiled memory image for a single database mapping relationship is thread-safe.
 -Sessionfactory objects are assigned specific configuration information once they are constructed
 -Sessionfactory is the factory that generated the session
 -construct sessionfactory Consumes resources, in general, only one Sessionfactory object is initialized in an application.
 -Hibernate4 A new Serviceregistry interface, all Hibernate-based configurations or services must be unified to this serviceregistry  to take effect br>  -The steps to create sessionfactory in Hibernate4 See Test class top three code
4-3.session Interface

A session is a single-threaded object that interacts between an application and a database and is the center of Hibernate operations, and all persistent objects must be managed by the session to be persisted. This object has a short life cycle. The session object has a first-level cache, and the data for all persisted layer operations is slowed down until the session object is persisted until flush is explicitly performed. Equivalent to Connection in JDBC.
Persistent classes have the ability to persist after they are associated with the Session.
Method of Session class:
-Method for getting persisted objects: get () load ()
-persisted objects have to be saved, updated and deleted: Save (), update (), Saveorupdate (), delete ()
-Open transaction: BeginTransaction ().
-Method of managing Session: IsOpen (), flush (), clear (), evict (), close (), etc.
4-4.transaction (Business)

Represents an atomic operation, which has the concept of a database transaction. All persistence tiers should be under transaction management, even read-only operations.
Transaction tx = Session.begintransaction ();
Common methods:
Commit (): submits the associated session instance
Rollback (): Undo transaction operation
Wascommitted (): Checks whether the transaction is committed


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.