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.Lesson AimsAt 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:

Code [ PR3 ]Segment 2.3: The Employee.hbm.xml FileIn 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.

Configuration SettingsIn 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:

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.

Configuration Settings Description
hibernate.dialect 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.

hibernate.connection.pool_size Specifies the figure of connexions that theHibernate database connexion pool should keep.
hibernate.connection.datasource 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 HibernateMaping through NotesTraditional 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 NotesIn 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.7: Making aSessionObjectAfter 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.

Transaction PropertiesA 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.

Transaction RollbacksA 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 HibernateHibernate 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:

  • Which one of the undermentioned elements will you utilize in a Hibernate constellation file to end product the Hibernate generated SQL to the console?
    1. & A ; lt ; belongings name = “ hibernate_show_sql ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;
    2. & A ; lt ; belongings name = “ hibernate.show.sql ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;
    3. & A ; lt ; belongings name = “ hibernate.sql_show ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;
    4. & A ; lt ; belongings name = “ hibernate.show_sql ” & amp ; gt ; true & A ; lt ; /property & A ; gt ;

    Answer: Calciferol

    1. 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.

    1. & A ; lt ; mapping map= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;
    2. & A ; lt ; mapping resource= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;
    3. & A ; lt ; mapping package= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;
    4. & A ; lt ; mapping file= ” org/hibernatedemo/domain/Account.hbm.xml ” / & A ; gt ;


    Glossary [ A16 ]

    Written by

    I'm Colleen!

    Would you like to get a custom essay? How about receiving a customized one?

    Check it out