Hibernate Official Document Translation-(chapter II, Getting started)

Source: Internet
Author: User

Chapter Two: Using Native Hibernate APIs and hbm.xml mappings

(Sample code download address http://sourceforge.net/projects/hibernate/files/hibernate4/) 2.1. Hibernate configuration file
The resource file Hibernate.cfg.xml defines the hibernate configuration information.
For example, connection.driver_class,connection.url,connection.username and Connection.password attribute elements define the information for JDBC connections. Because this tutorial takes advantage of the H2 "in-Memory" (in-memory) mode, the values of these properties are the specific values that run on the in-memory mode of H2. Connection.pool_size is used to configure the number of connections in the Hibernate built-in connection pool.
(Important: The Hibernate built-in connection pool is not intended for production environments and lacks many of the features of a connection pool in a production environment.)
The "dialect" attribute specifies the target-specific SQL variant (such as the specific statements of MySQL, the specific statements of Oracle, etc.) that will be converted by hibernate.
(Hint: In most cases, hibernate can correctly determine what kind of dialect to use, which is useful for applications that face multiple databases).
The "Hbm2ddl.auto" property allows hibernate to generate simple metadata outlines (such as databases, database table structures, and so on) directly to the database.
Finally, add a mapping file to the configuration for the persisted class, and the mapping element's "resource" attribute prompts Hibernate to attempt to locate the mapping as a resource for the classpath and use Java.lang.ClassLoader to search for it.
2.2. Entity class
The entity class for this tutorial is org.hibernate.tutorial.hbm.Event.
A description of the entity class:
The event class uses the standard JavaBean naming conventions to generate getter and setter methods for attributes, and all fields are private, although this is the recommended design method, but it is not necessarily necessary.
Also serves as the parameterless constructor of the JavaBean naming convention, as well as all persisted classes. Because hibernate needs to use the reflection mechanism to create objects for these classes for us. The construction method can be private, but the package is visible or globally visible (package or public visible) is a must for run-time generation agents and non-bytecode debugging efficient data retrieval.
2.3. mapping file
The mapping file Hbm.xml path for this tutorial is/org/hibernate/tutorial/hbm/event.hbm.xml.
Hibernate uses mapped metadata to determine how to load and store persistent objects, Hibernate mapping files are an option for hibernate to provide these metadata.


Example: 2.1 Class Mapping element
<class name= "Event" table= "EVENTS" >
...
</class>


The function of the class element:
The 1.name property specifies the name of the entity class that will be persisted (to combine the package attribute).
The 2.table property specifies the database table that contains the entity data.
With the class attribute, all instantiated objects of the event class are now in the events table in the database
Line one by one corresponds.


Example: 2.2 ID mapping element
<id name= "id" column= "event_id" >
...
</id>
Hibernate uses the specified property value of the ID element to uniquely flag each row in the table.


(IMPORTANT: The ID element does not have to be mapped to the primary key (primary key) in the table, but this is a traditional practice.) Tables that are mapped in Hibernate do not even require a primary key. Nevertheless, it is strongly recommended that all metadata define referential integrity. Therefore, IDs and primary keys are interchangeable in hibernate documents.


The ID element flags the event_id column as the primary key for the events table, and also flags the ID field of the class event containing the value of the unique flag.


The generator element is nested inside the ID element to tell hibernate which policy to use to generate the primary key for the entity class.


Example: 2.3. Property mapping Properties
<property name= "Data" type= "timestamp" column= "Event_date"/>
<property name= "Title"/>


The above two property elements declare the remaining two fields of the event: date and title. The Date property contains the column property, but the title property does not. If you do not specify the column property, Hibernate uses the same property name as the column (column) name. Title just makes the class field name consistent with the database table column name, but because date is the key reserved for most databases, you need to specify a different column name for date.
The type attribute is missing from the title element, and the type attribute in the mapping file is neither a Java type nor a type in the SQL database, but rather a hibernate mapping type. The Hibernate mapping type is a translator that acts as a translation officer between Java and SQL. If the type attribute is not specified in the mapping, Hibernate automatically attempts to use the correct conversion, which is judged by the Java reflection mechanism.


In some cases this automatic probing may not select the default type that you expect or need, as in the case of the Date property, hibernate cannot know whether the Java.util.Date type should be mapped to date,time or timestamp type in SQL. The full date and time information in the mapping file should be mapped to the timestamp converter, which is the Org.hibernate.type.TimestampType type in Hibernate.


2.4. Sample Code
Class Org.hibernate.tutorial.hbm.NativeApiIllustrationTest shows how to use the Hibernate local API.
(Hint: All the sample code for the tutorial is tested under JUnit, and for easy, one way is to build and destroy Sessionfactory separately under @before and @after).
Example: 2.4. Access to Org.hibernate.SessionFactory

protected void Setup () throws Exception {
    //a program sessionfactory as long as the creation of
    sessionfactory = new Configuration ()
            . Configure ()//Configures settings from Hibernate.cfg.xml
            . Buildsessionfactory ();


Work Flow:
1. Load configuration file
The first to detect the configuration file is the Org.hibernate.cfg.Configuration class. All configuration details for this tutorial are in Http://hibernate.org/documentation/quickstart/en-US/html/ch02.html#hibernate-gsg-tutorial-basic-config
2. Create Org.hibernate.SessionFactory
Then org.hibernate.cfg.Configuration creates the Org.hibernate.SessionFactory object, the Org.hibernate.SessionFactory object is a thread-safe object that only needs to be instantiated once in the entire application (single case mode).
3.SessionFactory Create session instance.
Sessionfactory as a factory for the session instance, you can see it in the Testbasicusage method in the sample code.
4.Session Objects Start working
A Session object should perform a single unit of work.


Example: 2.5. Depositary Entities (persistent entities)
Session session = Sessionfactory.opensession ();
Session.begintransaction ();
Session.save (New Event ("Our very-a-event!", New Date ());
Session.save (New event ("A Follow Up event", New Date ());
Session.gettransaction (). commit ();
Session.close ();




The Testbasicusage method first creates some event objects and passes them to hibernate management using the Save method, hibernate is responsible for inserting them into the database using the INSERT statement.


Example: 2.6. Get a series of entity objects
Session = Sessionfactory.opensession ();
Session.begintransaction ();
List result = Session.createquery (' from Event '). List ();
For (Event event: (list<event>) result) {
    System.out.println ("event () + event.getdate () +"): "+ event.ge Ttitle ());
}
Session.gettransaction (). commit ();
Session.close ();




Testbasicusage shows how to use Hibernate query Language (hql:hibernate query language) to load all event objects in the database, generating the appropriate select SQL statements, Sends to the database and populates the event object with the returned result set.


2.5. More in depth ...
Hands-on Practice:
"Reconfigure the sample code to connect to your own database

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.