Hibernate: Participant Guide
Lesson 2: Acquiring Started with Hibernate
You can utilize Hibernate as an ORM model in a Java application by supplying function metadata through XML-based constellation files or by utilizing Java Persistence API ( JPA ) notes in the relentless categories. In add-on to configuring the function metadata [ PR1 ] , you need to configure Hibernate on how to utilize the database that your application will entree. You can configure Hibernate through a bequest Java belongingss file or an XML-based Hibernate constellation file. After you configure Hibernate, you can utilize the categories and interfaces of the Hibernate API to manage the continuity demands of your application.
In this lesson, we will larn about the minutess in Hibernate and how to log into Hibernate.
At the terminal of this lesson, you will be able to:
- Describe object-relational function in Hibernate through constellation files and notes
- Explain Hibernate session mill and session
- Describe how to pull off minutess in Hibernate
- Integrate Spring with Hibernate
- Explain how to log SQL questions through the Hibernate constellation file
- Use log4j to execute logging
Subject 1: Function Concepts and Configuration
The Hibernate model allows you to specify how relentless categories should be mapped with database tabular arraies. You can specify the function information of a relentless category in an XML-based constellation file. The sentence structure for calling this function file is as follows:
In the predating sentence structure, & A ; lt ; persistent_class_name & A ; gt ; is the name of the relentless category.
For illustration, you create the employeetbl tabular array as shown in Code Segment 2.1:
Code Segment 2.1: Script to Make theemployeetblTable
Next, you create the Employee category in a Hibernate application as shown in Code Segment 2.2. The objects of this category can be persisted to the employeetbl tabular array:
Code Segment 2.2: TheEmployeeClass[ PR2 ]
In order to map the belongingss of the Employee category with the employeetbl database tabular array, you can make anEmployee.hbm.xmlfile, as shown in Code Segment 2.3:
Code [ PR3 ]Segment 2.3: The Employee.hbm.xml File
In Code Segment 2.3, the Employee category contains the Idaho, name, section, and age belongingss along with their corresponding getter and compositor methods.
The function file in Code Segment 2.3 contains the function of the Employee category with the employeetbl tabular array. This file contains the & A ; lt ; hibernate-mapping & A ; gt ; root component that contains the undermentioned sub-elements:
- & A ; lt ; category & A ; gt ;: Maps the Employee category to the employeetbl tabular array. This component contains the & A ; lt ; Idaho & A ; gt ; element that maps the id belongings of the Employee category to the EMP_ID primary cardinal column of the tabular array. The & A ; lt ; generator & A ; gt ; component has a category property that specifies native as an alias name of a org.hibernate.id.IdentifierGenerator execution. The native value for the category property instructs Hibernate to utilize an appropriate cardinal coevals algorithm, such as individuality, sequence, or hilo [ PR4 ] based on the capablenesss of the database.
- & A ; lt ; belongings & A ; gt ;: Is used to map the belongingss of the Employee category with the specific columns of the employeetbl tabular array. For illustration, the name belongings of the Employee category, which is of type String, is mapped to the EMP_NAME column of the employeetbl tabular array.
In add-on to the function information, you besides need to supply the constellation scenes related to database connectivity, mapping paperss, and other parametric quantities that affect the behavior of Hibernate at runtime. You can stipulate the constellation scenes in a Java belongingss file, namedHibernate.propertiesor an XML-based constellation file, namedHibernate.cfg.xml.
Hibernate provides default values for most of the constellation scenes. However, you need to explicitly stipulate scenes, such as the database URL, user name, watchword, and the function files to utilize, which are required by your application to put to death.
Code Segment 2.4 shows the Hibernate constellation file that defines how to link with the trial MySQL database to prevail an Employee object whose function is defined in theEmployee.hbm.xmlmapping file:
Code Segment 2.4: The Hibernate Configuration File
When you develop a new Hibernate application, you can get down developing the application before making the database. [ PR5 ] In such a scenario, you can teach Hibernate to export scheme Data Definition Language ( DDL ) to the database based on the function metadata by adding the undermentioned belongings component to the constellation file:
The predating [ PR6 ] belongings component uses the hbm2ddl tool to automatically make the database tabular arraies based on the function metadata when the session mill is created. Some extra constellation scenes that you can utilize to configure Hibernate are listed in Table 2.1.
Specifies the SQL idiom of the implicit in database. From Hibernate 4.0 onwards, you can exclude this scene because Hibernate automatically determines the idiom to utilize based on the database connexion scenes.
Specifies the figure of connexions that the
Hibernate database connexion pool should keep.
Specifies the JNDI name of the informations beginning for container deployed applications.
Specifies the URL of the JNDI supplier for container deployed applications.
Table 2.1: Configuration Settingsto Configure Hibernate
Maping through Notes
Traditional Hibernate applications used XML files to stipulate function metadata. With the debut of Java SE 5 notes, Hibernate provides support to stipulate the function metadata through notes in the relentless category. Although Hibernate still supports mapping through XML files, in big applications with considerable figure of relentless objects, the procedure to make and keep a corresponding XML function file for each persistent object non merely becomes cumbrous and mistake prone, but besides unwieldy. Therefore, the recommended pattern is to utilize notes that provide a more elegant and flexible manner of declaring functions. In add-on, the most widely used Java Integrated Development Environments ( IDEs ) , such as Eclipse and Netbeans, support notes through refactoring, automatic codification completion, and syntax highlighting. Hibernate implements the JPA specifications, and you can utilize the JPA notes in a relentless category to supply mapping metadata to Hibernate.
Hibernate follows conventions to map annotated persistent categories. Therefore, even if you do non footnote all the belongingss of a category, Hibernate will automatically map the belongingss based on conventions. For illustration, even if you do non declare every belongings of a category to be relentless, Hibernate, by default, will presume the belongingss to be relentless. You can overrule this default behavior by utilizing the @ Transient note. Similarly, even if you do non explicitly stipulate a column name to map a belongings, Hibernate will presume the belongings name as the name of the column. This reduces the sum of codification you will necessitate to compose as compared to the traditional XML function files.
Code Segment 2.5 shows the Employee category that uses notes, alternatively of the function file, to stipulate mapping metadata:
Code Segment 2.5: TheEmployeeClass[ PR7 ]with Mapping Notes
In Code Segment 2.5, the Employee category uses the undermentioned JPA mapping notes present in the javax.persistence bundle:
- @ Entity: Declares the Employee category as a relentless category.
- @ Table: Maps the Employee category to the employeetbl tabular array.
- @ Id: Maps the id belongings to the EMP_ID column.
- @ GeneratedValue: Specifies that the primary key will be car generated by the database.
- @ Column: Maps a belongings to a column in the employeetbl tabular array.
After you have annotated the relentless category with the function metadata, you need to teach Hibernate to utilize the annotated category alternatively of the function file. For this, you will necessitate to update the & A ; lt ; mapping & A ; gt ; component of the Hibernate constellation file, as shown in the undermentioned codification section:
Subject 2: Hibernate Session
A Hibernate session represents a communicating channel between an application and the database. You create [ PR8 ] a Hibernate session from a SessionFactory object, which in bend is provided by a Hibernate Configuration object. This object is an execution of the org.hibernate.cfg.Configuration category and represents the constellation scenes that are specified in the Hibernate constellation file. Normally one Configuration object is created in an application. After you create a Configuration object, you need to name the configure ( ) method to utilize the functions and belongingss specified in the hibernate.cfg.xml file.
Note: If you use a different name for the Hibernate constellation file, such asApplication.cfg.xml, you need to go through the file name as the parametric quantity to the overladen configure ( ) method.
After you have initialized the Configuration object, you need to make a SessionFactory object through a ServiceRegistry object. A SessionFactory object is an changeless object and does non retain any association with the Configuration object. A common attack in Hibernate applications is to make a public-service corporation category that provides SessionFactory objects to the application.
Code Segment 2.6 shows the HibernateUtil category with the inactive createSessionFactory ( ) method that returns a SessionFactory object:
Code Segment 2.6: TheHibernateUtilClass
In an Hibernate application, you can name the createSessionFactory ( ) method of the HibernateUtil category to obtain a SessionFactory object. You can so name the openSession ( ) method of the SessionFactory category to obtain a Session object. Code Segment 2.7 shows how to make a Session object from a SessionFactory object:
Code Segment 2.7: Making aSessionObject
After you obtain a Session object, you can execute the Create, Read, Update, and Delete ( CRUD ) operations within a dealing.
[ PR9 ]
Subject 3: Minutess in Hibernate
When you develop an endeavor application, you must place the operations required to implement a specific map of the application. This is peculiarly indispensable when the operations need to entree and pull strings the informations stored in a information beginning. It is of import [ PR10 ] that these types of related informations entree operations execute as a unit to turn to the concern demands of the application. It is every bit of import [ PR11 ] to guarantee that the set of operations does non put to death at all if a individual operation of the unit fails to put to death. You can turn to these demands by utilizing minutess in Hibernate.
A dealing is a individual atomic [ PR12 ] unit of work where multiple operations occur in sequence. In a dealing, all the operations defined for the dealing will either successfully complete or neglect even if one of the defined operations of the unit fails.
In the context of minutess, ACID is used as an acronym to specify the undermentioned four cardinal dealing belongingss:
- Atomicity: Specifies that a dealing should be considered a individual unit of operation that consists of a sequence of independent operations, where all the operations complete either successfully or unsuccessfully.
- Consistency: Ensures that the database is in a valid province while a dealing ends. This means that even if the dealing fails, the province of the database remains the same as it was before the dealing started.
- Isolation: Ensures that multiple minutess that occur at the same time remain stray from each other, to forestall informations corruptness.
- Lastingness: Ensures that the consequences of a successful dealing are lasting, irrespective of any system failure.
A dealing can be either committed or rolled back. When a dealing is committed, all the operations defined in sequence for the dealing must put to death successfully. If a individual operation in the dealing unit fails, the full dealing axial rotations back.
To understand dealing push back, see a scenario where you are at a manifold film counter to purchase film tickets for yourself every bit good as three friends. A manifold executive of a booking counteris in the procedure of delegating seats to the engagement. After the executive has assigned three seats a system failure occurs on the computing machine of the executive. Without minutess, the three assigned seats will be stored in the database and won’t be available for booking. However, when you move to a different engagement counter, you find that the seats are shown to be available. This happens because a dealing push back occurred when the system failed in the first counter and the full sequence of operation to book the tickets was non committed to the database.
A dealing push back occurs when one of the operations performed in a sequence for a transactional unit fails. A transactional push back must guarantee database consistence. This means that the push back should non go against the unity of the stored informations in the database before the dealing started.
Transaction API in Hibernate
Hibernate provides the org.hibernate.Transaction interface that abstracts an application from the underlying dealing direction executions, such as JDBC and JTA minutess. You need to name the beginTransaction ( ) method of the current session to get down a dealing. The beginTransction ( ) method returns a Transaction object. After the set of informations entree operations completes, you can name the commit ( ) method on the Transaction object. If any exclusion is thrown during the session, you can name the push back ( ) method on the Transaction object to rollback the dealing.
Code Segment 2.8 shows a typical execution of dealing in a Hibernate application:
Code Segment 2.8: Implementing Transaction
Subject 4: Integrating Spring with Hibernate [ A13 ]
Proxy for demo [ PR14 ]
Subject 5: Logging in Hibernate
A primary demand of Hibernate applications is to log the SQL statements that Hibernate generates. This is peculiarly of import when you need to analyse public presentation jobs or other bugs that exist in the application. In add-on, you can analyse the generated SQL statements to find and analyze the figure of questions that Hibernate executes to finish an ORM undertaking. This helps you to utilize indices and other database scenes to optimise the questions. One manner to log the SQL statements that Hibernate generates is to put the hibernate.show_sql belongings to true in the Hibernate constellation file.
A true value of the hibernate.show_sql belongings writes all the SQL statements that Hibernate generates in the Eclipse console.
Figure 2.1 shows the SQL statements that Hibernate generates in the Eclipse console.
Figure 2.1: Hibernate Generated SQL Statements in the Eclipse Console
Although utilizing the hibernate.show_sql belongings is simple, it is non flexible because it will merely end product the generated SQL to the console. The generated SQL on the console tends to acquire cluttered with other log statements of the application. This makes it hard for developers to turn up and analyse the statements. In add-on, when you use the hibernate.show_sql belongings, you can non see the parametric quantity values passed in the prepared statements. These values are represented with the? symbol, as shown in Figure 2.1.
To run into the logging demands of your application, you can utilize a logging model, such as Log4j.
Loging through Log4J
From Hibernate version 4.0 onward, Hibernate has integrated the JBoss Logging library that acts as a span to incorporate logging models, such Log4j. To utilize the Log4j logging model, you need to configure the build way of your undertaking in Eclipse to add the Log4j JAR file.
After you add the Log4j JAR file to your undertaking classpath, you need to add a log4j.properties file to the src booklet of your undertaking to specify the logging constellations, as shown in Code Segment 2.9:
Code Segment 2.9: Specifying Log4j Properties
Thelog4j.propertiesfile in Code Segment 2.9 end products log messages to thehibernateapp.logfile in theTocopherolthrust and besides to the Eclipse console.
Figure 2.2 shows the log messages of Log4j with the binding parametric quantity values in the Eclipse console.
Figure 2.2: Log Messages of Log4j in Eclipse Console
Figure 2.3 shows the log messages of log4j directed to thehibernateapp.logfile:
Figure 2.3: Log Messages of Log4j in hibernateapp.log File
[ PR15 ]
Lab Exercise 1: Exploitation Hibernate to Persist Data utilizing JPA note with logging log4j
Check your Understanding
- Which notes are compulsory in a relentless category?
Answer: At the lower limit, you must stipulate the @ Entity and @ Id notes in a relentless category. Although the @ GeneratedValue note is normally used in a relentless category, it is non compulsory. If you do non utilize the @ GeneratedValue note, you must manually delegate an identifier to an object of the category before Hibernate persists the object to the database.
- Which one of the undermentioned elements will you utilize in a Hibernate constellation file to end product the Hibernate generated SQL to the console?
- & A ; lt ; belongings name = “ hibernate_show_sql ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;
- & A ; lt ; belongings name = “ hibernate.show.sql ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;
- & A ; lt ; belongings name = “ hibernate.sql_show ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;
- & A ; lt ; belongings name = “ hibernate.show_sql ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;
- Which one of the undermentioned elements will you utilize in a Hibernate constellation file to include anAccount.hbm.xmlmapping file. Assume that you have created theAccount.hbm.xmlfile for an Account category in theorg/hibernatedemo/domainbundle.
- & A ; lt ; mapping map= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;
- & A ; lt ; mapping resource= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;
- & A ; lt ; mapping package= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;
- & A ; lt ; mapping file= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;