Book Image

Java Hibernate Cookbook

Book Image

Java Hibernate Cookbook

Overview of this book

This book will provide a useful hands-on guide to Hibernate to accomplish the development of a real-time Hibernate application. We will start with the basics of Hibernate, which include setting up Hibernate – the pre-requisites and multiple ways of configuring Hibernate using Java. We will then dive deep into the fundamentals of Hibernate such as SessionFactory, session, criteria, working with objects and criteria. This will help a developer have a better understanding of how Hibernate works and what needs to be done to run a Hibernate application. Moving on, we will learn how to work with annotations, associations and collections. In the final chapters, we will see explore querying, advanced Hibernate concepts and integration with other frameworks.
Table of Contents (15 chapters)
Java Hibernate Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Providing an XML-based hibernate mapping


In the preceding recipe, you learned how to create a POJO. Now we will consider how to create the configuration for hibernate. There are multiple ways of mapping, and this is one of them.

Generally, the configuration provides the following information:

  • The mapping between the POJO and the database table

  • The mapping between the POJO property and the database table column

  • The definition of the primary key column

  • The definitions of the foreign key column and relationships such as one-to-one, one-to-many, many-to-one, many-to-many with another table, and so on

  • Constraints such as not-null, formula, lazy, cascade, and so on

  • The definitions of the length, the data type of the column, the formula, and so on

How to do it…

To provide hibernate mapping based on XML, perform the following steps:

  1. Ensure that the basic structure of the configuration file is as follows:

    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD X.X//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-X.X.dtd">
    <hibernate-mapping>
    ...
    </hibernate-mapping>

    Note

    We have not provided the DTD code for the future demo in this book, but it should be present while developing.

  2. Create a XML file and name it Employee.hbm.xml. Then, add the configuration, as shown in the following code:

    <hibernate-mapping>
      <class="Employee" table="employee">
        <id name="id" type="long" column="id">
          <generator class="increment" />
        </id>
        <property column="firstName" name="firstName" />
        <property column="salary" name="salary" />
        <!-- other properties mapping-->
      </class>
    </hibernate-mapping>

    Note

    Here, we named the mapping file Employee.hbm.xml. However, while developing, there is no strict rule regarding the naming convention. Here, we will create a new hbm file for each POJO; for example, we created an Employee.hbm.xml file for the Employee.java class. Another common practice we will use here is to create one hbm file for the module, map all the classes of this module in the same mapping file, and name this file modulename.hbm.xml.

How it works…

Here, <hibernate-mapping> is a root element that contains all the <class> elements. The <class> tag contains the following attributes:

  • name: This specifies the FQN (Fully Qualified Name) of the Java class.

  • table: This denotes the database table used for the class defined in the name attribute.

  • The <generator> tag in the <id> tag is used to generate the value of the primary key. There are many types of built-in generators provided by hibernate, such as identity, sequence, hilo, and so on.

The <id> tag defines the primary key column for the database table. It contains the following attributes:

  • name: This specifies the Java class attribute name

  • column: This denotes the database table's column name

  • type: This specifies the data type of the column that will help hibernate during the creation and retrieval of the automatic table

  • size: This denotes the size attribute that defines the length of the table's column

Note

The type attribute in the <id> and <property> tags helps hibernate to create a table structure automatically for us using the hbm mapping.

Usually, we create a mapping file called hbm (hibernate mapping). It is a normal XML schema file that contains custom hibernate XML tags. This helps the hibernate engine to map the class to the table and the class field to the table column, along with the given attributes.

All the mapping definitions for hibernate are bundled under the <hibernate-mapping> ... </hibernate-mapping> tag. In <hibernate-mapping> ... </hibernate-mapping>, we can add any number of class-to-table mapping definitions.

Tip

It is good practice to provide the type in mapping because if this attribute is not provided, hibernate needs to use reflection to get the data type of the field; reflection requires a little more processing than a normal execution does.

There's more…

Now, let's create the XML mapping for the POJO having a reference with another POJO. Here, we will create two different mapping files. To achieve this using an XML-based mapping, we have to create different class mappings for each POJO that has a dependency.

The following is a code that represents the mapping for the Department class. The mapping is in the Department.hbm.xml file:

…
<hibernate-mapping>
  <class name="Department" table="department">
    <id name="id" type="long" column="id">
      <generator class="auto" />
    </id>

    <property column="deptName" name="deptName" />
    <!-- other properties mapping -->
  </class>  
</hibernate-mapping>
…

Next, we will create a mapping for the Employee class. Its definition is present in the Employee.hbm.xml file:

…
<hibernate-mapping>
  <class="Employee" table="employee">
    <id name="id" type="long" column="id">
      <generator class="auto" />
    </id>

    <property column="firstName" name="firstName" />
    <property column="salary" name="salary" />
    <many-to-one name="department" class="Department" >
      <column name="department"/>
    </many-to-one>
    <!-- other properties mapping-->
  </class>
</hibernate-mapping>
…

In the preceding example, we mapped the Department entity with the Employee entity. This will refer to the department column in the employee table. This means that it will create a foreign key that is referenced to the department table.

Here, we will use the <many-to-one> relationship, which means that either many employees are connected with one department, or one department is used by many employees.

The properties are as follows:

  • not-null="true": This property prevents the user from inserting the NULL value in the column

  • lazy="true": This feature helps us while retrieving data using hibernate

The two possible options for lazy are true and false. In our example, Employee is a parent class, whereas Department is a child of the Employee class. Now, while fetching, if we set lazy as true, it means that it will only fetch employee records. No child records will be fetched with Employee, and hibernate will use a separate query if we try to access a child record, which is employee.getDepartment(). If we set lazy as false, hibernate will fetch the child records with the parent, which means that the department information will also be fetched, along with that of the employee. Hibernate will use a join query to fetch the child records.