Hibernate Simple Example Basics Insert Record

Hibernate Simple Example Basics Insert Record


Hibernate Simple Example

Note: This notes on Hibernate Example gives the basic steps of writing a Hibernate program. Explained in simple steps.

Here, a Student record is inserted into database table using Hibernate. All the code is explained very clearly with the relevant XML files. The execution part of this program is given separately in Simple Hibernate Program – Step-by-step Execution with screenshots. It advised to read the Hibernate Tutorial before going into this program.

First let us go for a simple program where a Student object is inserted (persisted) into Oracle database table school.

Student class school table in Oracle database
Java Instance variable Type Table Column name Type
sid int STUD_ID (primary key) number(4)
sname String STUD_NAME VARCHAR2(15)
smarks double STUD_MARKS number(4,1)
sjoindate Date STUD_JOIN-DATE date

Create a table school as follows in the database and keep it ready.

SQL> create table school (STUD_ID number(3) primary key, STUD_NAME varchar2(15), STUD_MARKS number (4,1), STUD_JOIN_DATE date);

Shall I disclose one more strength of Hibernate? Hibernate creates the table (on the same name of the class) with all the columns (on the names of instance variables) by default when it does not exist; this we explore later.

Now you are ready with school table and further require 4 programs.

  1. Student.java – Java class written with JavaBean syntax.
  2. hibernate.cfg.xml – A Configuration file
  3. student.hbm.xml – A Mapping file.
  4. StudentClient.java – Java Client program that inserts (or stores or persists) Student objects in database.

Now let us see each of the above 4 files and discuss line-wise.

1. Java program Student.java with JavaBean syntax with setter and getter methods (Persistent class)

The variables of this Java program correspond to columns in a database table. We create an object Student class, set the properties and persist (storing) in database table school.

In JavaBean syntax, each property is represented by one instance variable. Every property should have one set and one get method. Here, four properties are declared as sid, sname, smarks and sjoindate. Values for these variables are given in client program. Values given are placed in the database table school.

The Student class implements Serializable interface for object persistence. The class should follow JavaBean syntax rules like having a default constructor and setter and getter methods.

I used purposefully different data types so that a learner gets acquainted of their usage in Hibernate.

Now you are ready with the class Student and table school.

It requires two XML files – hibernate.cfg.xml and student.hbm.xml.

2. Configuration File – hibernate.cfg.xml

This file comes with Hibernate software distribution. Just override as per your convenience. This XML file mainly tells Hibernate what database you are using to insert the data along with user name and password etc. The file should have an extension .cfg.xml

The syntax is almost self explanatory but for a few. Dialect tells the name of the database we are using. Hibernate supports Oracle. The other databases Hibernate supports are given at the end of this notes.

<session-factory> is responsible to connect to database. Programmer should provide all the required information in the form of XML tags. The first five <property> elements give the database specific information including the driver being used. The information of this XML file is used by SessionFactory object in the client program to connect to database. If the same Java bean values (called as properties) are to be inserted in multiple databases (like one table in Oracle and one table in MS-Access etc.), multiple SessionFactory objects are required. Of course, do not worry about SessionFactory now itself.

orcl is the service name, the programmer configured while installing the Oracle.

SNRaoConnection is the database connection created in Database Explorer (of MyEclipse) earlier.

show_sql shows on the Console (of MyEclipse), the SQL statements created by Hibernate implicitly to insert the records. See at the end of this notes for screen shots.

Student.hbm.xml is the XML file where mappings between Java variables and database columns are given.

3. Mapping File – Student.hbm.xml

This XML file tells what instance variable of Student class is to be mapped to what column of table school.

The file should have an extension .hbm.xml. The name is given as Student just to remember Student.hbm.xml file belongs to class Student, but for it can be any name.

This is the heart of the entire Hibernate where programmer writes instructions to Hibernate how it should behave with Java variables and database columns. There must be a primary key in the table and the primary key here is STUD_ID corresponding to sid in the Student bean class. Let us go in detail.

Element Name Functionality
<hibernate-mapping> It is the root element of the above XML mapping file. <class> element is the child element of it.
<class> This element contains all the mapping information of which Java bean variable (or field or property) is to be mapped to which database column. The "name" attribute should be given the name of the Java bean class (here, it is Student) and "table" attribute should be given the name of the database table (here, it is school).
<id> This element gives Hibernate the primary key information of the table. "name" attribute gives the name of the Java bean variable. The "column" attribute gives the table column name. Here the value of sid is to be inserted into stud_id column of table school. stud_id works as primary key. "type" attribute is given value as integer. The integer value is the data type of Hibernate and not of Java. The integer value converts sid int value to database specific SQL column type (in Oracle, it is number).
<generator> This describes the primary key assignment. The primary key value can be assigned by the programmer himself or can be asked the Hibernate to assign a value by itself as per its algorithm. Here, the value assigned tells Hibernate that primary key value is assigned by the programmer himself. How to tell the Hibernate to generate itself (where programmer will not give), we will see later.
<property> This element tells Hibernate which bean field to be mapped to which table column. The "name" attribute should be given the name of the bean field (or instance variable) name and "column" attribute should be given the name of the column in datable table. In the first property, the value of sname of Student class should be inserted into the stud_name column of school table. The "type" attribute value refers Hibernate string (not Java String) which at runtime converts sname String value to database specific column type (in Oracle, it is varchar).

The type integer, string, double and date are the data types of Hibernate not of Java which at runtime converted to database specific (here, it is Oracle) column types.

4. Client program – StudentClient.java

Finally we write a client program which when executed inserts records in the database table.

Configuration c = new Configuration();
c.configure(“/hibernate.cfg.xml”);

The starting point of the client program is creating an object of Configuration class. Configuration object, here it is c, job is to load the hibernate.cfg.xml file, read the database particulars and return these particulars to SessionFactory object sf.

Session s = sf.openSession();

The Session object is equivalent to Connection object of JDBC. Any data to be persisted in the database is passed to Session object (say, save()), here it is s.

Creation of Transaction object tx is required for all save, delete and update operations. Select statements (reading records) do not require. Transaction object dictates the boundaries of transaction with beginTransaction() and commit() (or rollback()) methods.

Student std1=new Student();
std1.setSid(100);
std1.setSname(“S N Rao”);
std1.setSmarks(78);
std1.setSjoindate(new Date());

Two Student objects std1 and std2 are created and properties are set with setXXX() methods as declared in Student bean program.

s.save(std1);
s.save(std2);

The save(), update() and delete() methods of Session class do not insert data immediately. Instead, these methods write addBatch() statements and keep ready for execution. The flush() method internally writes one executeBatch() statement and executes all the addBatch() statements. This style increases considerable performance.

tx.commit();

The commit() method of Transaction does commit operation on the statement executed earlier with flush() method.

Following is the screenshot of Console of Hibernate. The screen shows the SQL statements created by Hibernate internally to insert std1 and std2 objects in the database (this is the effect of show-sql attribute in hibernate.cfg.xml file. If this attribute is omitted, the SQL statements created and executed by the Hibernate are not seen).

Hibernate Example

After the client program execution, check your database whether the Java objects are persisted (in the form of records) or not. Following is the screenshot of the database after executing the client program.

Hibernate Example

Dialects (databases) supported by Hibernate

Hibernate supports following databases.

Cache71Dialect, DataDirectOracle9Dialect, DB2390Dialect, DB2400Dialect, DB2Dialect, DerbyDialect, FirebirdDialect, FrontBaseDialect, H2Dialect, HSQLDialect, InformixDialect, Ingres10Dialect, Ingres9Dialect, IngresDialect, InterbaseDialect, JDataStoreDialect, MckoiDialect, MimerSQLDialect, MySQL5Dialect, MySQL5InnoDBDialect, MySQLDialect, MySQLMyISAMDialect, Oracle10gDialect, Oracle8iDialect, Oracle9Dialect, Oracle9iDialect, OracleDialect, PointbaseDialect, PostgresPlusDialect, PostgreSQLDialect, ProgressDialect, SAPDBDialect, SQLServer2008Dialect, SQLServerDialect, Sybase11Dialect, SybaseDialect, SybaseAnywhereDialect, TeradataDialect, TimesTenDialect etc.

class attributes (in hibernate.cfg.xml file)

Following are the most frequently used values.

  1. increment: It increments itself and generates ID of type short, int or long.
  2. identity: It is specific for DB2, MySQL server, Sybase etc. The generated type may be short, int or long.
  3. sequence: To generate an ID, the database uses a sequence execution. The generated type may be short, int or long.
  4. hilo: High-low generator internally uses a hi/lo algorithm to generate identifiers of data type short, int and long.
  5. native: It takes some algorithm like sequence, identity or hilo specific to the database.
  6. assigned: Here, programmer should assign the ID for himself.
  7. foreign: It uses an ID of another associated object; generally used in one-to-one association.

7 thoughts on “Hibernate Simple Example Basics Insert Record

  1. Prakhar

    How many pojo we should create for any project, please anwer this queation sir I am very much confused how to create a complete project with hibernate so many tutorials are there which provides logic and explanation for persisting only one pojo class instance, but how to create a complete project ?

Leave a Reply

Your email address will not be published. Required fields are marked *