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
Java Hibernate Cookbook
Java Hibernate Cookbook

Java Hibernate Cookbook: Over 50 recipes to help you build dynamic and powerful real-time Java Hibernate applications

Arrow left icon
Profile Icon Prajapati Profile Icon Ranapariya
Arrow right icon
€36.99
Paperback Sep 2015 250 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Prajapati Profile Icon Ranapariya
Arrow right icon
€36.99
Paperback Sep 2015 250 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Java Hibernate Cookbook

Chapter 1. Setting Up Hibernate

In this chapter, we will cover the following recipes:

  • Getting the required libraries for hibernate
  • Creating a hibernate persistent class
  • Providing an XML-based hibernate mapping
  • Providing an annotation-based hibernate mapping
  • Providing a hibernate configuration using an XML file
  • Providing a hibernate configuration using a properties file
  • Configuring hibernate programmatically

Introduction

In this chapter, we will take a look at how the hibernate and ORM (Object-relational Mapping) frameworks work, how to configure hibernate in different ways, and the libraries that are required for the hibernate application. An essential part of the application is the hibernate configuration. Through the configuration, we can provide database information to the hibernate engine, such as the database host, port, username, password, the database name, the drive class, and so on.

In the older era of Java development, developers used some methodologies to persist data. To persist data means to save or store data in some storage medium by maintaining it in a certain state. Once the data is successfully persisted, it can be used at any given time. A database is the more preferable storage medium for a transactional operation. Usually, we use JDBC (Java Database Connectivity) to perform such operation with the database.

If we use the JDBC operation, we need to work a bit harder and take care of the following processes:

  • Opening a database connection
  • Maintaining an open connection
  • Building a query
  • Executing a query
  • Getting a response to the query
  • Mapping the query response with the custom classes
  • Closing the database connection

To avoid this hectic process, we can use the ORM tools available in the market. ORM stands for Object Relation Mapping. It works as a bridge between the application and database by simplifying the communication between them.

The benefits of the ORM framework are as follows:

  • It reduces the development time/cost.
  • It speeds up the development.
  • It provides us with portability. Hibernate supports multiple databases, so there is no need to write a database-specific code.

This is a useful feature of hibernate. Generally, all databases have their own syntax made up of Data Definition Language (DDL) or Data Manipulation Language (DML) statements. If we used JDBC, we would need to write a database-specific code as our database is changed. However, hibernate gets rid of the developer's headache by handling this issue.

The syntax of a query may be different for different database parameters; still, hibernate works in the same way for all types of databases. Hibernate's term dialect helps achieve this type of functionality. The implementation of the dialect class is provided by the database provider to inform hibernate about the syntax of this particular database.

Some useful features of hibernate are as follows:

  • Code reusability
  • Transaction management
  • Efficient collection/custom classes mapping
  • The caching mechanism supported by hibernate

Getting the required libraries for hibernate

To work with hibernate, we need a JAR (Java Archive) file provided by hibernate. Here, we will see how to download the hibernate core distribution. There are multiple ways to get the required libraries; here, we will consider two of them:

  • Manually downloading
  • Using Maven

Manually downloading

The first and most basic JAR file needed is a JDBC driver. The JDBC driver is a bridge or an API between Java and the database. The JDBC driver provides us with the generic classes that will help us communicate with the database. Generally, the driver is either provided by the database provider or developed by communities; however, you have to get it yourself. This also depends on the type of the database you are using. As we will use the MySQL database for this book, we will use the Mysql-Connector.jar file.

How to do it…

Let's come back to the library section. Apart from JDBC, you will need the JAR files for hibernate. Perform the following steps:

  1. Download the hibernate core distribution from http://hibernate.org/orm/.
  2. Now, place all the files in your classpath if you plan to run a standalone program and put them in the lib folder if it's a J2EE project.

Note

When you manually download the libraries, it's the programmer's responsibility to get all the required and dependent JAR files from the official site of hibernate; failing this, they will face errors.

Using Maven

If you use the Maven project, it would get rid of your headache of finding all the JAR files for hibernate and the dependent libraries. You can use the following Maven configuration for hibernate.

How to do it…

  1. Enter the following code into the pom.xml source file to show the dependency mapping of hibernate and MySQL in pom.xml:
    …
    <dependencies>
      <!-- MySQL connector -->
      <dependency>
        <groupId>MySQL</groupId>
        <artifactId>MySQL-connector-Java</artifactId>
        <version>MySQL-connector-version</version>
      </dependency>
     
      <!-- Hibernate framework -->
      <dependency>
        <groupId>hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>hibernate-version</version>
      </dependency>
    <dependencies>

Using this method, Maven will download all the required JAR files related to hibernate and the dependent libraries required for hibernate.

Note

Replace MySQL-connector-version with your required MySQL connector version in the <version>MySQL-connector-version</version> line, and replace hibernate-version with your required hibernate version in the <version>hibernate-version</version> line.

Creating a hibernate persistent class

As discussed in the Preface, the developer will be dealing with objects at every step of development. Also, when we use hibernate, we don't need to work on a core SQL query. Here, we will create a POJO (Plain Old Java Object) in Java, which represents a table in the database.

Getting ready

By POJO, we mean that we will create a Java class that satisfies the following requirements:

  • It needs to have a default constructor that is persistent.
  • It should contain the id attribute. ID is used to identify the object and is mapped with the primary column of a table.
  • All attributes should have Getter and Setter methods, such as getXXX and setXXX where xxx is a field name.

How to do it...

We will now create a persistent class and name it Employee. The following table shows a representation of the Employee class:

Employee

id

firstName

salary

  1. Create the Employee.java class and place the following code in the class:
    public class Employee{
      private long id;
      private String firstName;
      private double salary;
      // other fields
    
      // default constructor
      public Employee() {
      }
    
      public long getId() {
           return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getFirstName() {
        return firstName;
      }
    
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
    
      public double getSalary() {
        return salary;
      }
    
      public void setSalary(double salary) {
        this.salary = salary;
      }
      
      //
      // Getter and setter for other fields...
      //
    
    }

Now the preceding class satisfies all the requirements listed before to be a persistent class.

The preceding class now contains the following:

  • The default Employee() constructor
  • The id attribute, which is the primary column of the table and can be used to uniquely identify an entry
  • The individual getters and setters in all the attributes (id, firstName, and salary)

There's more…

Now, let's see how to design a POJO for tables having references between the Department and Employee tables:

There's more…

The following code is the definition for the Department class in Department.java:

public class Department{
  private long id;
  private String deptName;

  //default constructor
  public void Department(){
  }

  //getters and setters
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getDeptName() {
    return deptName;
  }

  public void setDeptName(String deptName) {
    this.deptName = deptName;
  }

}

The following code is the definition for the Employee class in Employee.java:

public class Employee{
  private long id;
  private String firstName;
  private double salary;
  private Department department; // reference to Department.

  //default constructor
  public void Employee(){
  }

  //getters and setters
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public double getSalary() {
    return salary;
  }

  public void setSalary(double salary) {
    this.salary = salary;
  }

  public Department getDepartment(){
    return department;
  }

  public setDepartment(Department department){
    this.department = department;
  }
  
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

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.

Providing an annotation-based hibernate mapping

When we choose the annotation-based way to provide a configuration, we don't need to create any hibernate mapping (usually *.hbm. xml) file. Hibernate provides the annotations that we can directly write to the POJO, and we can provide all the mappings via the classes, which we can do using the previous XML file.

How to do it…

Now, let's create the class that contains the annotation-based mapping. As we used the Employee class to provide XML-based mapping here, we will use the same class with annotations:

  1. Represent the annotation-based mapping for the Employee class in Employee.java, as shown in the following code:
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="employee")
    public class Employee{
    
      @Id
      @Column(name="id")
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;
    
      @Column(name="firstname")
      private String firstName;
    
      @Column(name = "salary")
      private double salary;
    
      // default constructor
      public Employee() {
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getFirstName() {
          return firstName;
      }
    
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
    
      public double getSalary() {
        return salary;
      }
    
      public void setSalary(double salary) {
        this.salary = salary;
      }
    
    }

How it works…

Now, compare the annotations with the XML mapping to gain a better understanding of the difference between the two methods.

Declaring a class — Table for the database

In the annotations, we will write the following code:

@Entity
@Table(name="employee")
public class Employee{...}

Now, check the XML mapping for the same here:

<class name="Employee" table="employee">

The keywords used in the preceding class are described below:

  • @Entity: This annotation declares the class as an entity bean.
  • @Table: We can set this annotation at the class level only. You can provide the name attribute, which is considered as a database table name. You can also just write @Table without any attribute; in this case, the class name is considered as a table name by hibernate.

Declaring an ID — The primary key for the table

In the annotations, we will write the following code:

@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

Now, check the XML mapping for the same in the following code:

<id name="id" type="long" column="id">
  <generator class="auto" />
</id>

The annotations used in the preceding code are described below:

  • @Id: This annotation declares the property to be an identifier property, and this is used as a primary key for the table.
  • @Column: This annotation is used to define the column for the table. Here, we used name="id", meaning that hibernate considers the column name to be "id". You can also write @Column without any attributes; in this case, the property name is considered to be a column name for the table.
  • @GeneratedValue: Using this annotation, we can provide information to hibernate on how to generate a value for the primary key column. Here, we will use strategy = GenerationType.AUTO, which means that hibernate uses the autoincrement value for the id column. If not provided, hibernate uses the most appropriate generation strategy.

Referencing an object

In the annotations, we will write the following code:

@JoinColumn(name="department")
@ManyToOne
private Department department;

Now check the XML mapping for the same in the following code:

<many-to-one name="department" class="Department">
  <column name="department"/>
</many-to-one>

The annotations used in the preceding code are described below:

  • @JoinColumn: This annotation notifies hibernate that this is a reference column.
  • @ManyToOne: This annotation defines the relation between the referenced tables. Here, we have used many-to-one, meaning that one department can be mapped with multiple employees.

There's more…

In the previous section you learned how to reference a class using hibernate. In this section, we will take a look at how to provide the reference of one class in another class in detail.

Do not get confused when writing Employee.java again to show the reference object annotation.

The following code represents the annotation-based mapping for the Employee class that has the reference field in Employee.java:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="employee")
public class Employee{

   @Id
   @Column(name="id")
   @GeneratedValue(strategy = GenerationType.AUTO)
   private long id;
   
   @Column(name="firstname")
   private String firstName;
   
   @Column(name = "salary")
   private double salary;
   
   @JoinColumn(name="department")
   @ManyToOne
   private Department department;
   
   // default constructor
   public Employee() {
   }
   
   // getters & setters
   public long getId() {
   return id;
   }
   
   public void setId(long id) {
   this.id = id;
   }
   
   public String getFirstName() {
   return firstName;
   }
   
   public void setFirstName(String firstName) {
   this.firstName = firstName;
   }
   
   public double getSalary() {
   return salary;
   }
   
   public void setSalary(double salary) {
   this.salary = salary;
   }
   
   public Department getDepartment(){
   return department;
   }

  public setDepartment(Department department){
    this.department = department;
  }
}

The following code represents the annotation-based mapping for the Department class in Department.java:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table //If name is not supplied hibernate will use class name as table name
public class Department{
  @Id
  @Column //If name is not supplied hibernate will use field name as column name
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @Column
  private String deptName;
  
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getDeptName() {
    return deptName;
  }

  public void setDeptName(String deptName) {
    this.deptName = deptName;
  }

}

Providing a hibernate configuration using an XML file

In the preceding discussion, you learned how to create a class and provide a mapping to hibernate. These mappings show the relationship between the Java class and the database table.

Still, hibernate requires some information about the database, host, and port, on which the application is running. It also requires information about the username and password to access the database. Hibernate uses this set of configurations to connect to the database.

This is a traditional way to provide the hibernate configuration; however here, we need to create an XML file, generally called hibernate.cfg.xml, in the classpath. There is no strict rule to name it hibernate.cfg.xml; we can give it a custom name instead of hibernate.cfg.xml, in which case, we need to instruct hibernate to load the configuration from the particular file. Otherwise, hibernate looks for the file named hibernate.cfg.xml in the classpath.

How to do it...

Now, we will create the XML file that shows the configuration for MySQL:

  1. Enter the following code in hibernate.cfg.xml to show the configuration for the applications:
    ...
    <hibernate-configuration>
      <session-factory>
    
      <property name="hibernate.dialect">
        org.hibernate.dialect.MySQLDialect
      </property>
      <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
      </property>
      <property name="hibernate.connection.url">
        jdbc:mysql://localhost:3306/kode12
      </property>
      <property name="hibernate.connection.username">
        root
      </property>
      <property name="hibernate.connection.password">
        root
      </property>
      <property name="show_sql">true</property>
      <property name="hbm2ddl.auto">update</property>
    
      <!-- List of XML mapping files -->
      <mapping resource="Employee.hbm.xml"/>
      <mapping resource="Department.hbm.xml"/>
    
      </session-factory>
    </hibernate-configuration>

How it works...

Here, we will take a look at only the basic configuration parameters. Let's understand the meaning of each property:

  • <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>: This property helps hibernate to generate database-specific SQL statements. This is an optional property. According to hibernate documentation, hibernate will be able to choose the correct implementation of dialect automatically using the JDBC metadata returned by the JDBC driver.
  • <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>: Using this property, we can provide the Fully Qualified Name (FQN) of the java driver name for a particular database. The driver class is implemented using Java and resides in the JAR file and contains the driver that should be placed in our classpath.
  • <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/kode12</property>: Using this property, we can provide the physical location of the database; however, the connection URL may vary from database to database. Here, we will use the MySQL database, so the URL shows jdbc:MySQL://<host/computer-name/ip>:<port>/<database name to connect>.
  • <property name="hibernate.connection.username">root</property>: Using this property, we can provide the username to access a particular database.
  • <property name="hibernate.connection.password">root</property>: Using this property, we can provide the password to access a particular database.
  • <property name="show_sql">true</property>: The possible value for this property is either true or false. This is an optional property. Hibernate logs all the generated queries that reach the database to the console if the value of show_sql is set to true. This is useful during basic troubleshooting. Hibernate will use the prepared statement so that it does not display the parameter in the output window. If you want to see this parameter as well, you will have to enable the detailed log. Log4j is preferred for the detailed log.
  • <property name="hbm2ddl.auto">create</property>: The possible values are validate, update, create or create-drop. This is also an optional property. Here, we will set value=create so that it will remove all the schemas and create a new one using the hibernate mapping on each build of sessionfactory. For value=update, hibernate will update the new changes in the database.

    Note

    Do not use the hbm2ddl.auto property in the production environment because it may remove all of the data and schema. So, it's best practice to avoid it in the production environment.

  • <mapping resource="Employee.hbm.xml"/>: All of the mapping file is declared in the mapping tag, and the mapping file is always named xx.hbm.xml. We can use multiple mapping tags for multiple mapping files.

    Here is an example:

    <mapping resource="Employee.hbm.xml"/>
    <mapping resource="Department.hbm.xml"/>

There's more…

Here are some useful properties used in hibernate:

  • hibernate.format_sql:
    • The possible values are true and false
    • It shows the hibernate-generated queries in the pretty format if set as true
  • hibernate.connection.pool_size:
    • The possible value is always greater than 1 (value >= 1)
    • It limits the maximum number of pooled connections
  • hibernate.connection.autocommit:
    • The possible values are true and false
    • It sets the autocommit mode for JDBC

Providing a hibernate configuration using the properties file

This is another way to configure hibernate; here, we will create a file with the .properties extension. Usually called hibernate.properties, this file is a replacement for hibernate.cfg.xml. You can use any approach (either cfg.xml or the properties file). However, the properties file is better for startup, and it is the easiest approach to get started quickly.

This is a simpler representation of an XML file. Hibernate searches for the XML file or the properties file at startup to find the configuration in your classpath. We can use any one of these options. You can use both of them at the same time, but this is uncommon because hibernate gives priority to the XML file over properties; the properties file is simply ignored in such cases.

Note

The properties file looks similar to a normal text file, but the content should be in a key/value pair, which is Key=Value.

Here is an example: hibernate.connection.driver_class=com.mysql.jdbc.Driver.

How to do it…

Now, we will create a file called hibernate.properties in our classpath and write the following properties in the file. The following code represents hibernate.cfg.xml in the hibernate.properties file:

…
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/kode12
hibernate.connection.username=root
hibernate.connection.password=root
show_sql=true
hbm2ddl.auto=update
…

How it works…

When we create an instance of the Configuration class, it will look for hibernate.cfg.xml or hibernate.properties in our classpath. If we use a .properties file, it'll get all of the property defined in the file, rather than create a Configuration object.

Note

The difference between an XML and properties file is that, in an XML file, you can directly map classes using the <Mapping> tag, but there is no way to configure it in a properties file. So, you can use this methodology when you use a programmatic configuration.

Configuring hibernate programmatically

In the preceding section, we understood XML and the properties-based configuration. Hibernate also supports the programmatic configuration. To configure hibernate using this method, we have to work on a Java code and create an instance of the org.hibernate.cfg.Configuration class. There are multiple ways to configure hibernate.

How to do it…

First, write the following code:

Configuration configuration = new Configuration();

This will create an instance of the Configuration class using hibernate.cfg.xml or hibernate.properties, whichever is found in the classpath.

Provide the following mapping files to the configuration:

configuration = configuration.addResource("Employee.hbm.xml");
configuration = configuration.addResource("Department.hbm.xml");

You can use an alternate way, as shown in the following code:

Configuration configuration = new Configuration().addResource("Employee.hbm.xml").addResource("Department.hbm.xml");

We can also provide a direct mapping using the class, as shown in the following code:

configuration = configuration.addClass("Department.class");

This will also look for Department.hbm.xml.

We can also set a custom property. To set up the custom property, use the following method:

configuration.setProperty(propertyName, value);

For example, consider the following code:

configuration.setProperty("show_sql", true);

To set up multiple properties using the properties object, execute the following code:

configuration.setProperties(java.util.Properties properties);

Here is an example:

Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/kode12");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "root");
properties.put("show_sql", "true");
properties.put("hbm2ddl.auto", "update");
configuration.setProperties(properties);

To read the mapping from the URL, you can use the following code:

configuration = configuration.addURL(java.net.URL url);

To read the mapping from the XML file, you can use the following code:

configuration = configuration.addXML(String xml);

How it works…

When we select the programmatic configuration option, the Configuration class is very important. Using the instance of the Configuration class, we will build a SessionFactory object, as shown in the following code:

SessionFactory sessionFactory = new Configuration().buildSessionFactory();

When the preceding code is executed, it creates a SessionFactory object using a .properties or .cfg file or whichever source is provided to create the configuration.

Left arrow icon Right arrow icon

Key benefits

  • Learn to associate JDBC and Hibernate with object persistence
  • Manage association mappings, implement basic annotations and learn caching
  • Get to grips with Hibernate fundamentals from installation to developing a business application with this step-by-step guide

Description

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.

Who is this book for?

This is book for Java developers who now want to learn Hibernate. Good knowledge and understanding of Java is preferred to allow efficient programming of the core elements and applications; it would be helpful if readers are familiar with the basics of SQL.

What you will learn

  • Set up and install Hibernate on your system and explore different ways in which Hibernate can be configured
  • Learn the basic concepts and fundamentals of Java Hibernate
  • Define mappings without a use of XML file using Annotations
  • Persist collection elements such as list, map, set and array
  • Explore the various mapping options and learn to work with Hibernate associations
  • Understand advanced Hibernate concepts such as caching and inheritance
  • Develop an engaging and robust real-world hibernate application based on a common business scenario
  • Integrate Hibernate with other frameworks to develop robust enterprise applications
Estimated delivery fee Deliver to Sweden

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 18, 2015
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391904
Vendor :
Oracle
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Sweden

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Sep 18, 2015
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391904
Vendor :
Oracle
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 103.97
Mastering Hibernate
€24.99
Test-Driven Java Development
€41.99
Java Hibernate Cookbook
€36.99
Total 103.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Setting Up Hibernate Chevron down icon Chevron up icon
2. Understanding the Fundamentals Chevron down icon Chevron up icon
3. Basic Annotations Chevron down icon Chevron up icon
4. Working with Collections Chevron down icon Chevron up icon
5. Working with Associations Chevron down icon Chevron up icon
6. Querying Chevron down icon Chevron up icon
7. Advanced Concepts Chevron down icon Chevron up icon
8. Integration with Other Frameworks Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela