Hibernate Simple Program Step-by-step Execution

Hibernate Program Execution

After creating a database connection, now let us execute our first program. In this program, we create a "Student" class with four fields (instance variables) sid, sname, smarks and sjoindate. The values given to these fields, at runtime from client program, should be entered in the Oracle database table "school". This is the aim of this simplest Hibernate program where the execution steps are learnt.

Before going into the program, keep ready the school table in the Oracle database with the following columns. (Alternatively, the Hibernate is so powerful it can also create itself a database table if one does not exist. This option (hbm2ddl.auto), we see later.)

Note: This gives only screens of execution, actual program notes is available separately at Simple Example Basics – To insert a Record.

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

Hibernate places the values of sid in STUD_ID , sname in STUD_NAME and so on.

Create a table 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);

1st Program: Student.java

1. Now change the Perspective to "MyEclipse Java Enterprise".

You will get a window like this:

Hibernate Program Execution

2. In the empty space of the left top panel known as "Package Explorer", right click and select "new" option. In the option, select "Java Project" and enter some project name; here, I entered as "Program1_Student". By default, a folder by name src is created under the project space Program1_Student.

3. Right click on src, and select "Class". You will get a dialog box like this. To make the coding simple, here we are not creating a package (of course, not advisable). This we will do in later programs.

Hibernate Program Execution

Fill up the text boxes as follows.

Name: Student
Constructors from superclass: select the checkbox

When Student is entered, you will see by default:

a) public radio button is selected among Modifiers
b) java.lang.Object is filled up in Superclass text box
c) checkbox "inherited abstract methods" selected.

Keep the default settings as it is, then, click Finish button.

4. You will get Student class opened in the editor (the central panel) as follows.

Hibernate Program Execution

Write the Student class with JavaBean syntax. Declare (manually write) some instance variables (known as fields or properties) as follows in the Student class.

private int sid;
private String sname;
private double smarks;
private Date sjoindate;

Select all the four fields in the editor, right click on the selected fields, select Source option, in the submenu, select Generate getters and setters option. Select, Select All option where all checkboxes of all fields are selected. Now click OK button. Now getter and setter methods are added. Save the file.

5. One more task is adding Hibernate capabilities (it is nothing but adding Hibernate packages).

If we do not add the Hibernate capabilities, later the client program does not compile, and moreover, we do not get hibernate.cfg.xml file by default.

a) Right click on the project space (not on src folder) FirstProgram_Student –> MyEclipse –> Add Hibernate Capabilities as follows.

image

b) You get a screen as follows:

Hibernate Program Execution

Select Hibernate 3.2 radio button (by default Hibernate 3.3 is selected). By default the two check boxes were selected as shown in the above dialog box. Click Next button.

c) You get another screen as follows.

Hibernate Program Execution

By default, the radio button "New" of "Hibernate config file" is selected and also the check box "Open configuration file after wizard completion".

Click Next Button.

d) Now you a get screen as follows.

image

By default, the check box "Specify database connection details?" is selected and also the radio button "Use JDBC Driver".

It is the wizard where you show the Oracle database particulars to Hibernate to persist the Java object. Now your job is easy as you have created a database connected "SNRaoConnection" earlier. Now let us link it to this wizard. (if you have not created earlier, fill each text box one-by-one manually).

DBDriver: Select the "SNRaoConnection" from the drop down list (it comes automatically in the drop down list).

Automatically all the text boxes in the above wizard are filled up except Password text box. Now fill it with "tiger".

Finally the above wizard looks as follows.

Hibernate Program Execution

Click Next Button.

e) You get a screen as follows.

image

By default, the check box "Create SessionFactory class?" is selected. Deselect it (observe, all the text boxes are disabled). This option we will use later (in the second program – Employee).

Click Finish button.

You get Hibernate.cfg.xml which you can edit further.

6. Editing Hibernate.cfg.xml file

Hibernate Program Execution

You can observe, in the above wizard, one file "hibernate.cfg.xml" is created in Package editor (left panel). Right click on this file and open in a Text editor (or alternatively choose Source tab at the bottom). It looks as follows.

a)
Hibernate Program Execution

You can check the contents and get satisfied.

Now you must add three more xml tags (first two are optional) just before closing tag. You can type these manually.

<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="Student.hbm.xml"/>

(actually, these three statements can be added through the wizard also which we will do it later in the second program – Employee).

Now the file (hibernate.cfg.xml) looks like this.

image

7. Create one file by name Sudent.hbm.xml

If you got any similar file, copy it to src folder (rename with Refactor) and overwrite the tags. Finally the file looks like as follows as required for our Student class.

image

After adding the above three tags, just save and come out.

8. Now create a client program in the same src folder. File Name: StudentClient.java

Right click on the src folder –> New –> Class.

Select the main() method check box, give the file name as StudentClient and then click Finish button. By default, the StudentClient.java file is placed in the default package (where the bean exists).

Write the following code and save.

import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class StudentClient 
{
	/**
	 * @param args
	 */
  public static void main(String[] args) 
  {                                       // TODO Auto-generated method stub
		                          // create Configuration class
		                          // Configuration parses and reads .cfg.xml file
    Configuration c = new Configuration();
    c.configure("/hibernate.cfg.xml");
				          // SessionFactory holds cfg file properties
		                          // driver props, hibernate properties and mapping file
    SessionFactory sf = c.buildSessionFactory();
	 		                  // creating session equals to Connection object creation
    Session s = sf.openSession();
		                          // before starting save(),update(), delete() operation we need to start Transaction
		                          // starting Transaction means con.setAutoCommit(false);
    Transaction t = s.beginTransaction();

    try
    {
      Student s1 = new Student();
      s1.setSid(100);
      s1.setSname("S N Rao");
      s1.setSmarks(45.6);
      s1.setSjoindate(new Date());
      s.save(s1); 
      s.flush(); 
      t.commit();
      System.out.println("Record Inserted");
    }
    catch(Exception e) 
    {
      System.out.println(e);
      t.rollback();
    }
  }
}

Execute the above program, check in the database, the record is inserted.

Finally, at the end of the application, the MyEclipse is screen is seen like this.

Hibernate Program Execution

Left side Package Explorer, in the above screen, is shown separately in the next screen, to know the files etc. used in the application.

Hibernate Program Execution

In the above screen:

JRE System Library [JavaSE-1.6] is added when you write a Java class where you selected JavaSE-1.6 (of course, default) as your JDK.

Hibernate 3.2 Annotations & Entity Manager and Hibernate 3.2 Core Libraries are added when you loaded the JAR files with "Hibernate Capabilities".

ojdbc14.jar is added with "SNRaoConnection" (a database connection).

Note: The above screens and notes do not give the meaning of each tag and option. For this refer Hibernate material on introduction along with first program – Student notes.

Note: After the execution of this first program, go for the second program, Program 2 – Employee for modifications.

Understand and execute this program thoroughly and is needed for the second and third programs. These three programs (Student, Employee and Officer) give you the minimal understanding of Hibernate. It is very necessary to understand the remaining programs of Hibernate.

2 thoughts on “Hibernate Simple Program Step-by-step Execution”

Leave a Comment

Your email address will not be published.