Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java Hibernate Cookbook

You're reading from   Java Hibernate Cookbook Over 50 recipes to help you build dynamic and powerful real-time Java Hibernate applications

Arrow left icon
Product type Paperback
Published in Sep 2015
Publisher
ISBN-13 9781784391904
Length 250 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (10) Chapters Close

Preface 1. Setting Up Hibernate FREE CHAPTER 2. Understanding the Fundamentals 3. Basic Annotations 4. Working with Collections 5. Working with Associations 6. Querying 7. Advanced Concepts 8. Integration with Other Frameworks 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.

You have been reading a chapter from
Java Hibernate Cookbook
Published in: Sep 2015
Publisher:
ISBN-13: 9781784391904
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image