Hibernate: Simple_Example

This section is divided into two parts. The first part is a step-by-step to create a very simple Hibernate application that inserts a new record in the Database. The second part is to understand the code you have written in the application.

In this tutorial we are using Eclipse (Release 3.4.0) as our IDE.

  • You can download eclipse by choosing "Eclipse IDE for Java EE Developers" from www.eclipse.org/downloads/ or directly from here

First of all, we need to create the Database, and the table we are going to insert in.

  1. Prepare your Datasource and name it "UniversityDS"

    1. Create a new Database. To be consistent with the tutorial, name it "University".
    2. Create the table "Lecturer" with columns
      • ID (PK, int, not null)
      • FName (nvarchar(50), null)
      • LName (nvarchar(50), null)
      you can use this query

      Create Table Lecturer ( ID int, FName nvarchar(50), LName nvarchar(50), Primary Key (ID))

    3. Make your Database to a Datasource. To be consistent with the tutorial, name it "UniversityDS".
      • Go to Control Panel / Administrative Tools / Dara Sources / Add / SQL Server / Finish.
      • Name: UniversityDS Server: your SQL Server Name / Next.
      • Enter your SQL Server Authentication info / Next.
      • Check 'Change the default database to': Choose the DB 'University' / Next.
      • Finish / Ok / Ok.

  2. Create a Java Project and name it "HibernateHelloWorld"

    If this is your first time using eclipse, follow these steps:

    1. Open Eclipse. Go to the folder where you saved eclipse and double-click 'eclipse.exe'
    2. Choose your workspace. Browse to the directory that you need to use as a workspace. A workspace is the place where your projects are saved. You may use an already existing folder to function as a workspace, or create a new one by browsing to the directory that you need your workspace to be placed in (C for example), and then writing the workspace name you like (the folder will be created automatically).
    3. Go to the workbench. If the Welcome page is opened, you can reach the workbench by clicking this icon.
    4. Create the project.
      • Click file in the menu-bar / New / Project .
      • Select Java / Java Project
      • Name it "HibernateHelloWorld"
      • Click Finish

  3. Add Hibernate Jar files.

    To use Hibernate, Your application needs to use some Jar files that are available here.

    1. Unzip the downloaded file.
    2. In the Project Explorer view (at the left-side of eclipse. If not there, Click: Window / Show view / Project Explorer) R-Click your project / Build Path / Configure Build Path.
    3. Add External JARs / Go to the unzipped folder - Select All / Open / Ok.

    Reminder:

    In the Files and Classes section, we said that To build a Hibernate application, we need:

    1. Persistent classes. Those are classes representing the Database entity tables.
    2. Mapping files. Defining persistent classes and their attributes, and their corresponding database and columns.
    3. Hibernate Configurations settings. That shows hibernate how to obtain and manage the connections with the database.
    Now we are going to create these three files.

  4. Create The Persistent Class for the entity 'Lecturer'.

    1. Create a class. In the Project Explorer view, R-Click your project / New / Class.
    2. Name it 'Lecturer'.
    3. Click Finish.
    4. Place this code:

      public class Lecturer { private int ID; private String firstName; private String lastName; public int getID() { return ID; } public void setID(int id) { ID = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }

  5. Create The Mapping File for the Table 'Lecturer'

    1. Create an XML file. In the Project Explorer view, R-Click your project / New / File.
    2. Name it 'Lecturer.hbm.xml'.
    3. Click Finish.
    4. Open it with Text Editor. R-Click 'Lecturer.hbm.xml' / Open with / Text Editor.
    5. Place this code:

      <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping> <class name="Lecturer" table="Lecturer"> <id name="ID" type="int"> <generator class="increment"/> </id> <property name="firstName" column="FName" type="string"/> <property name="lastName" column="LName" type="string"/> </class> </hibernate-mapping>

  6. Create an XML for Hibernate Configurations 'hibernate.cfg.xml'.

    1. Create an XML file.
    2. Name it 'hibernate.cfg.xml'.
    3. Click Finish.
    4. Open it with Text Editor.
    5. Place this code:

      <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- ________________ To be Edited _________________ --> <property name="connection.url">jdbc_URL</property> <property name="connection.username">jdbc_Username</property> <property name="connection.password">jdbc_Password</property> <!-- _____________ End of To be Edited ______________ --> <property name="connection.driver_class"> sun.jdbc.odbc.JdbcOdbcDriver </property> <property name="dialect"> org.hibernate.dialect.SQLServerDialect </property> <property name="current_session_context_class">thread</property> <!-- _________ Defining the Mapping Files ___________ --> <mapping resource="Lecturer.hbm.xml" /> </session-factory> </hibernate-configuration>

    6. Replace jdbc_URL, jdbc_Username, and jdbc_Password, with their appropriate values.
      • The jdbc_URL should look like 'jdbc:odbc:UniversityDS'.
      • The Username, and Password are used for SQL Authentication. They are those you input to connect the SQL server. The Username is most probably 'sa'.

  7. Finally Test your Application

    1. Create a class.
    2. Name it 'SimpleTest'.
    3. Click Finish.
    4. Place this code:

      import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SimpleTest { public static void main(String[] args) { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); Lecturer lecturer1 = new Lecturer(); lecturer1.setFirstName("Fatma"); lecturer1.setLastName("Meawad"); session.save(lecturer1); tx.commit(); System.out.println ("The lecturer " + lecturer1.getFirstName()+ " " + lecturer1.getLastName()+" is successfully added to your database"); } }

    5. Run your application by pressing Ctrl + F11 / Java Application
    6. Check your Database.

    Hopefully, you are having a running Hibernate Application now. Proceed with reading to understand the code you have been pasting.

The application you have just created is having these files:

  1. The persistent class 'Lecturer.java'.
  2. Themapping file 'Lecturer.hbm.xml'.
  3. The Configurations file 'hibernate.cfg.xml'.
  4. The testing class 'SimpleTest.java'.

Now we are going to explain the code in these files.

  1. The persistent class 'Lecturer.java'.

    As explained in the previous section, we need to have a Class corresponding to each entity Table in our database. Instances of this class will be used to represent Database records. So accordingly the class should be able to carry data that can exist in such records, and since the table Lecturer is having the columns:

    • ID (int),
    • FName (nvarchar(50)), and
    • LName (nvarchar(50)).

    The corresponding class should be having a variable of type 'int' and two variables of type 'String'. In our example, they are:

    • int ID
    • String firstName
    • String lastName

    It is preferred not to provide a direct access to the variables but use accessor methods to the variables. Thats why the instant variables are 'private' and there is a getter and a setter method for each one. Hibernate can recognize accessor methods of the form getVariablename and setVariablename.

    Do not panic from the too much tedious work, since there are tools that automatically generate Persistent Classes and Mapping files like the Hibernate Synchronizer.

    Read more about Persistent Classes from JBoss Community Documentation.

  2. The Mapping file 'Lecturer.hbm.xml':

    The previous section showed that we need a mapping file to tell Hibernate, what Class is representing which Table, and what Instant Variable is corresponding to which Column.

    In our example, we have:

    • One Class 'Lecturer' that corresponds to the Table 'Lecturer', This is declared this way:

      <class name="Lecturer" table="Lecturer">

      This can be read: The class with the name 'Lecturer' is corresponding to the table 'Lecturer'.

      In this Class, there are the instant variables:

      • 'firstName' and 'lastName'.

        These variables are corresponding to the columns 'FName' and 'LName', This relation can be declared this way:

        <property name="firstName" column="FName" type="string"/> <property name="lastName" column="LName" type="string"/>
        • The property with the name 'firstName' is corresponding to the column 'FName'.
        • This property is of type 'string'.

        There are other attributes that are used with the element 'property' to guide Hibernate while creating the queries. These attributes are explained here.

      • ID

        This variable, in addition to corresponding to the column ID, is representing the primary key of the table... And since a role of a mapping file is to guide Hibernate while constructing the queries; Hibernate has to know, from a mapping file, how the Primary key is generated. Is it Identity, so the database will generate it ? Or the application will set it manually ? Or Hibernate will have to generate it ? ... etc.

        In our example, we declared it this way:

        <id name="ID" type="int"> <generator class="increment"/> </id>

        • The Primary key of the Table is represented by the instant variable with the name 'ID'.
        • The generator class of the Primary Key is 'increment'. This means that Hibernate is going to set it by incrementing the maximum ID value in the table by one. In other words, Hibernate will select the Max ID in the table; Add 1 to it; set the ID value of the new object to the calculated value.

          Learn more about the generator element from RoseIndia.

        • Note that the column attribute is not set. This is because the variable name is the same as the column name, and Hibernate's Default value for the column attribute is the value of the name attribute.

    Probably in other applications, you will have other questions about Mapping that hopefully you will find their answers here .

  3. Creating an XML for Hibernate Configurations 'hibernate.cfg.xml'

    The previous section stated that hibernate needs to know some information about the database and how to manage connections with it, and that this is information can be provided

    1. Programatically, or
    2. in XML file, or
    3. in .properties file

    In our example, we used an XML file for setting Hibernate Configurations.

    The file 'hibernate.cfg.xml' contained the very basic configurations needed to obtain and manage the connections; these configurations are:

    • The Datasource URL

      <property name="connection.url">jdbc_URL</property>

    • SQL Server Username and Password

      <property name="connection.username">jdbc_Username</property> <property name="connection.password">jdbc_Password</property>

    • The Driver Class

      <property name="connection.driver_class"> sun.jdbc.odbc.JdbcOdbcDriver </property>

    • The Dialect. It tells Hibernate about the Database it is going to generate its queries according to. (i.e. The syntax of queries generated for an SQL server database, is different from the syntax of queries generated for an Oracle database). And since we are using SQL Server, we use the Dialect 'dialect.SQLServerDialect' and represent it this way:

      <property name="dialect"> org.hibernate.dialect.SQLServerDialect </property>

      Here you can find a list of Dialects for different Databases.
    • The current_session_context_class, that tells Hibernate about how to bind the session.

      <property name="current_session_context_class">thread</property>

      The value 'Thread' means that the session will be binded "to the thread from which openSession(...) is called" // Source

    Read more about the Session Context or Hibernate Configurations by the JBoss Documentation Community.

  4. The testing class 'SimpleTest.java'.

    Finally, after all these preparations, we can now use Hibernate.

    As said before, Hibernate performs conversations with the database. These conversations are presented by the “session”. We obtain this session from the “SessionFactory” using the method “getCurrentSession()” or “openSession()”. For the SessionFactory, in order to be able to manage the sessions, it should be aware of the 'Configurations' we have just set. So we create an object of type “Configuration” that uses 'hibernate.cfg.xml'.

    So we need to,

    • Create the 'Configuration' object.

      Configuration configuration = new Configuration();

    • Ask it to compile our preset configurations.

      configuration.configure();

      This could have been done in the three ways we have mentioned before
      • Problematically, this way

        configuration.setProperty ("hibernate.connection.url", "jdbc_URL");

        Read more
      • In a .properties file. By default, a new Configuration object uses properties set in 'hibernate.properties'
      • In an XML by calling .configure method By default, the .configure() method uses the elements in 'hibernate.cfg.xml'. If you want to name your configurations file another name, you have to specify this file by calling one of the method's overloads, like for example:

        configuration.configure("conf.xml");

    • Create a SessionFactory with these configurations.

      SessionFactory sessionFactory = configuration.buildSessionFactory();

    • Start a DB Conversation by getting a Session

      Session session = sessionFactory.getCurrentSession();

    For less code, we have written the first three statements this way

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

    Now we have an opened conversation, we will enclose our commands in a Transaction

    Transaction tx = session.beginTransaction(); … tx.commit();

    Read about 'SessionFactory', 'Session' and 'Transaction' at JBoss Community Documentation .

    Since we wanted to insert a new record in table Lecturer, and Hibernate enables us to forget about records, so all we need is saving (i.e. create and save) a new Lecturer object

    Lecturer lecturer1 = new Lecturer(); lecturer1.setFirstName("Fatma"); lecturer1.setLastName("Meawad"); session.save(lecturer1);

    And this is the code you have pasted in SimpleTest.java

    Hibernate will

    • Find the Table corresponding to the Class 'Lecturer'
    • Find the Columns corresponding to the instant variables 'firstName' and lastName'
    • Check how the ID will be generated
      • The generator class is 'increment' (set in the mapping file)
      • Select the maximum ID from the table 'Lecturer', assume 7
      • Increment it by 1
      • Set the lecturer ID to 8
    • Execute this query:

      insert into Lecturer (FName, LName, ID) values ('Fatma','Meawad', '8')

    To be able to see the queries executed by Hibernate, add this statement to 'hibernate.cfg.xml'

    <property name="hibernate.show_sql">true</property>

Now we are done with our Simple Example, we should be moving to a more Advanced eExample, but first you need to know the different 'States of objects' in a Hibernate application.

Through out the previous part of the tutorial, we have been using the words 'Persistent' objects and 'Persistent' Classes. So what are persistent objects and what are other types of objects ?

Let's first define 'Persistence'... According to wikipedia, Persistence "refers to the characteristic of data that outlives the execution of the program that created it".

So, for example, If you are using a traditional calculator software, the data used in the application is not persistent, because once the application is closed, the data is not there any more (i.e. Data did not outlive "the execution of the program that created it"). But if your software saves the calculations in a database for example, this data is persistent (it "outlives the execution of the program that created it")

So accordingly, persistent objects are those objects whose data is not lost when the application is closed (i.e. There exist database records containing the exact values of the objects' variables).

Back to Hibernate objects' states; They are three states:

  1. Persistent state.

    The object is gauranteed to be representing a database record. These are objects attached to a Hibernate session. They are objects either saved , retrived ... etc by Hibernate.

    In our example, the object lecturer is persistent after this statment

    session.save(lecturer1)

  2. Transient state.

    Those are normal objects, used through out the application, and lose there values once the application is closed.

    In our example, the object lecturer is transient before this statment session.save(lecturer1)

  3. Detached objects.

    They are objects that where once persistent (attached to a certain context), but then this context is closed. It is not guranteed that this object is reflecting the database state.

    In our example, the object lecturer is detached after the statment

    tx.commit()

Test it yourself:

  1. Print the ID of the object lecturer1
    • Before session.save(lecturer1);
    • After session.save(lecturer1);

  2. Add lecturer1.setLastName("MEAWAD");
    • Between session.save(lecturer1); and tx.commit().
    • After tx.commit();
Watch what happens and analize it yourself.

Read about Hibernate Objects' states at JBoss comminity Documentation.

Keep these terms in mind, because we are using them in the Advanced Example next section.

RenewSession