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
€18.99 per month
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
€18.99 per month
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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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

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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.