By Subham Aggarwal | 4/12/2017 | General |Beginners

Hibernate - Session and Mappings in Persistence Classes

Hibernate - Session and Mappings in Persistence Classes

In this article, we’ll start by looking at Hibernate sessions which we touched on in last article, and then continue with how Mappings are used and managed using XML.

 

Hibernate is a complete solution for the persistence module in a Java project. It handles the application interaction with the database, leaving the developer free to concentrate more on business logic and solving complex problems.

Hibernate Sessions

Creating a session is like creating a physical connection with a database. Whenever we need an interaction with the database, we can create a session as they are very lightweight objects and are designed to be instantiated whenever a DB operation is required to be done. Persistent objects are saved and retrieved through session objects.

 

The session instances must not be kept open for a long time because they are not usually thread safe and they should be created and destroyed as needed. The key feature of the Session is to offer CRUD operations for instances of mapped persistence classes. When we instantiate a session object, it can live in three states at any time:

 

transient

A new instance of a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate.

 

persistent

We can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.

 

detached

After we close a session, the persistent instance will become a detached instance.

 

Key point to observe is that session instances are serializable if there persistent classes are serializable. Let’s look at how a typical transaction in our code should look:

Session sessionInstance = factory.openSession();
Transaction transaction = null;
try {
  transaction = sessionInstance.beginTransaction();
  // do our work

  ...
  transaction.commit();
}
catch (Exception e) {
  if (transaction != null)

      transaction.rollback();


  e.printStackTrace(); 
} finally {
  sessionInstance.close();
}

If the Session throws an exception, the transaction must be rolled back so that all changes are undone and the session must be discarded, or moved to detached state.

Persistence classes

The foundational concept of Hibernate is to read Java class attribute values and save them to the database. An XML-based mapping document helps Hibernate to pull the values based on identifiers and constraints and persist them according to database mappings.

 

Java classes whose objects or instances will be saved in the database are called persistent classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model. Here are the following simple rules of persistent classes, however, none of these rules are hard requirements:

 

  • A Required Persistent java class must have a default constructor.
  • All classes should contain an ID (unique identifier) in order to allow easy identification of the objects within Hibernate and the database. This property maps to the primary key column of a database table.
  • All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.
  • A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.
  • All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.

 

The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean.

 

Now that we have defined simple rules for making a persistent class, let us have a look at a sample POJO class:

public class Student {
  private int id;
  private String firstName; 
  private String lastName;   
  private float grade;  

  public Student() {}


  public Student(String fname, String lname, float grade) {
     this.firstName = fname;
     this.lastName = lname;
     this.grade = grade;
  }
  public int getId() {
     return id;
  }
  public void setId( int id ) {
     this.id = id;
  }
  public String getFirstName() {
     return firstName;
  }
  public void setFirstName( String first_name ) {
     this.firstName = first_name;
  }
  public String getLastName() {
     return lastName;
  }
  public void setLastName( String last_name ) {
     this.lastName = last_name;
  }
  public int getGrade() {
     return grade;
  }
  public void setGrade( float grade ) {
     this.grade = grade;
  }
}

Clearly, the code above is a simple POJO class with nothing special. Though this class is simple, it still needs a mapping document so that it is actually persisted when we start to perform our transactions on it. Let us define a mapping document.

Mapping files

Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate on how to map the defined class or classes to the database tables.

 

Though many Hibernate users choose to write the XML by hand, a number of tools exist to generate the mapping document like XDoclet, Middlegen and AndroMDA for advanced Hibernate users. If you are annotating your POJO's, you should definitely use Hibernate Annotations (or better: JPA). xDoclet was a good solution when Annotations were not available in Java.

 

If above defined persistent classes need to be saved to the database, let us first consider an RDBMS table as:

create table STUDENT (
  id INT NOT NULL auto_increment,
  first_name VARCHAR(20) default NULL,
  last_name  VARCHAR(20) default NULL,
  grade     DECIMAL(3,1)  default NULL,
  PRIMARY KEY (id)
);

Let us define our mapping document based on the POJO we defined earlier and the RDBMS table we just wrote:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
  <class name="Student" table="STUDENT">
     <meta attribute="class-description">
        This class contains the student detail. 
     </meta>
     <id name="id" type="int" column="id">
        <generator class="native"/>
     </id>
     <property name="firstName" column="first_name" type="string"/>
     <property name="lastName" column="last_name" type="string"/>
     <property name="grade" column="grade" type="float"/>
  </class>
</hibernate-mapping>

It is important to remember naming the file as <classname>.hbm.xml. I saved this file as Student.hbm.xml.

 

Let us add an explanation about the mapping elements we used in the mapping document:

  • The mapping document is an XML document having <hibernate-mapping> as the root element which contains all the <class> elements.
  • The <class> elements are used to define specific mappings from a Java class to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.
  • The <meta> element is an optional element and can be used to create the class description.
  • The <id> element maps the unique ID identifier in the class to the primary key of the DB table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
  • The <generator> element within the id element is used to automatically generate the primary key values. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create a primary key depending upon the capabilities of the underlying database.
  • The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type. This mapping type will convert from Java to SQL data type.

Conclusion

In this article, we studied Hibernate sessions and also learned how to define Hibernate persistent classes by defining appropriate mapping documents.

 

In an upcoming article, we will build upon these concepts to establish a fully working application in Hibernate which will perform simple CRUD operations on this entity.

By Subham Aggarwal | 4/12/2017 | General

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now