hibernate sample application with example

Hibernate is ORM(Object Relational Mapping) framework for mapping java object with database table. A brief description about Configuration, SessionFactory, Session, Query, Criteria, Transaction and follow the same for sample application creation using hibernate.

Configuration: Configuration is that the initial object you wish to make any of hibernate application and typically making one time throughout the applying initialization. It represents the configuration or properties file providing by hibernate.

SessionFactory: Configuration object is employed to make SessionFactory instance that intern configures hibernate for the applying. SessionFactory object is significant weight part, it's created throughout application start up time and unbroken for later use. The way to do this we are going to see in below application. We would like one SessionFactory object per info employing a separate configuration. Therefore if you victimization multiple databases then you'd ought to multiple SessionFactory objects.

Session: A session is employed to physically connect with table. A session object is lightweight and designed to be instantiated whenever interaction is required with table's. A session object mustn't unbroken open longer as a result of they're not sometimes thread safe and that they ought to be created and destroyed is needed.

Transaction: Transaction represents unit of labor with the table and most of the RDBMS supports dealings practicality. This can be associate degree elective object and hibernate applications might not to use this interface.

Query: Query object use for SQL or Hibernate search language (HQL) string to retrieve information from the database and make object.

Criteria: Criteria objects are create and execute Object Oriented criteria queries to retrieve object.

How to create sample hibernate application?
        First, we need to create Dynamic Web Project” by using any of the IDE’s. Then we need to add libraries (Net Beans), add external Jar (Eclipse) files based on the requirement. Now, I am doing hibernate simple application, I need to add hibernate jars for project class path.
How to add external jar’s for a project?
        This is very easy to add jar files to a project. Follow these steps, Right Click on project source folder --> select ‘properties’ --> choose ‘Java Build Path’ --> go into ‘libraries’  --> there you click on ‘Add External Jar’s’ --> choose your jar file’s in your local directory --> click on ‘Ok’ --> ’Ok’.
        In NetBeans is very easy to add libraries into a project. Follow these steps. Right click on project source folderàselect ‘libraries’ --> in that libraries choose required hibernate library. Also, add JDBC connection library in that libraries. Because, for connecting to database, that library is required. Once your adding jar/libraries into project libraries go into your created project and try to create source code.

        In hibernate we can interact java object with database table by using two ways. One is using hibernate mapping files and another one is using annotations.

        Here, I am going to explain a simple user login example by using hibernate mapping file. For that fist we need to create database table with related column's. Below query will be helpful for creating a data table with id, username and password columns in MySQL database.

Table:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
execute the below query for creating a database

CREATE database hibernatex;

execute the below command to use your newly creating database or existing database.

USE hibernatex;

execute the below query for creating the USER table with id, username and password fields.

CREATE table USER(
id integer(7) primary key not null,
username varchar(30),
password varchar(30)
);

        Here, I am creating a bean/POJO (Plain Old Java Object) class of employee with the properties which are matching to user table columns.

User.java:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.javatbrains.hibernate;

import java.io.Serializable;

public class User implements Serializable {
    
     private int id;
     private String userName;
     private String password;

     public int getId() {
          return id;
     }

     public void setId(int id) {
          this.id = id;
     }

     public String getUserName() {
          return userName;
     }

     public void setUserName(String userName) {
          this.userName = userName;
     }

     public String getPassword() {
          return password;
     }

     public void setPassword(String password) {
          this.password = password;
     }

}

        In User.java class contains iduserNamepassword of user and setters and getters methods of these properties. The User class should be implemented with  Serializable.

user.hbm.xml:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
     <class name="com.javatbrains.hibernate.User">
          <id name="id" type="int">
              <column name="ID" />
              <generator class="assigned" />
          </id>
          <property name="userName" type="java.lang.String">
              <column name="USERNAME" />
          </property>
          <property name="password" type="java.lang.String">
              <column name="PASSWORD" />
          </property>
     </class>
</hibernate-mapping>

        The above file shows you how the mapping file contains. User.hbm.xml file contains the mapping of User java class with USER table by using <class> hibernate tag which is present under  <hibernate-mapping> tag.
         <class> tag contains the <property>  tag for mapping the java class properties with table columns. <id> tag is the mandatory in the hibernate application.                                                         

Note: if you can’t specify the <column> tag, java class property name automatically taken by database table column name.

        Here, is the hibernate configuration file which is configured with the database, by declaring the property values are the database connection values.

hibernate.cfg.xml:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?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>
          <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property>
          <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/hibernatex </property>
          <property name="hibernate.connection.username"> root </property>
          <property name="hibernate.connection.password"> root </property>
          <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>
          <mapping resource= "com/javatbrains/hibernate/user.hbm.xml"
              package="com.javatbrains.hibernate.User" />
     </session-factory>
</hibernate-configuration>

        In the above configuration file contains the database properties of driver, connection url, username, password, dialect. Here, dialect is the vendor specific one, there I am using MySQL Dialect. If your using any other databases like, Oracle, postgreSQL. You must specify that particular vendor relesed dialect.

        Finally, I have mapped the user.hbm.xml file in hibernate.cfg.xml with package by using the <mapping> tag.

UserTest.java:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.javatbrains.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UserTest {

     public static void main(String[] args) {
          User us = new User();
          us.setId(2);
          us.setUserName("Java");
          us.setPassword("TBrains");
          try {
              SessionFactory sessionFactory = new Configuration().configure()
                        .buildSessionFactory();
              Session session = sessionFactory.openSession();
              Transaction transaction = session.beginTransaction();
              session.save(us);
              transaction.commit();
              session.close();
              System.out.println("Record Inserted");
          } catch (HibernateException he) {
              System.out.println("Hibernate has some exception for you: " + he);
          }
     }
}
  • In the above UserTest’ class, I am trying to insert User class object values into database 'USERtable. Here, you can see below steps to understand 'UserTestclass.
  • Create 'Userobject and set those values.
  • Create SessionFactory instance by using buildSessionFactory()  method in Configuration class.
  • Open a session instance by using the openSession() providing by SessionFactory interface.
  • Get Transaction instance by using beginTransaction() method providing by Session interface.
  • Use save (Object obj)saveOrUpdate (Object obj) to save Employee object values into database table.
  • Then commit transaction by using commit () method providing by Transaction interface.
  • Finally, close session by using close() method providing by Session interface.

Comments

Popular posts from this blog

how to count the page views by using JSP

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Multithreading in java with example