Hibernate is an Object relational mapping (ORM) tool , a solution for object-relation mapping and it is all about mapping the object properties to the table columns hence we can directly manipulate data contained in a relational database using an object.
The typical JDBC problems
Below are the some of the issues of using typical JDBC
1) Tied to specific database
2) Relationships are really hard.
3) In JDBC API, Exception handling is weak. There are only three types, SQL warning, SQL Error and data truncation exception and which are developed as checked exception. So every developer is forced to write the catch block.
4) When you use the JDBC connection you have to take care of many things while coding, like Concurrency,
5) Connection pooling, Transaction management, Performance of the query etc.
Advantages of using Hibernate
There are many advantages of using hibernate when comparing with typical JDBC,
1) As Hibernate is set of Objects it helps you to avoid SQL, you don’t need to learn SQL language.You can treat TABLE as an Object .
2) Powerful object-oriented hibernate query language .
3) Maps Java Beans to tables,
4) Descriptive O/R Mapping through mapping file.
5) Automatic primary key generation
6) Hibernatre is database independent,It is not specific for a particular data base. The same code will work for all data bases like ORACLE,SQLServer,MySQL etc. If you to change the database all you need to do is just change the configuration file.
7) Query optimization: If you use Criteria Quires in Hibernate then hibernate take of the query performance. In case of JDBC you need to tune your queries.
8) First level caching and Second level caching which has vital role in the performance.
9) We can utilize Inheritance concept
10) We can make use of User defined data type .In case of DB, only some database offer this feature, but if you migrate to other database it will be difficult.
Hibernate Configuration- First Hibernate
The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create the SessionFactory, which in turn creates the Session instances.
Hibernate.cfg.xml has the following format.
<?xml version=’1.0′ encoding=’utf-8′?> <!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”> <hibernate-configuration> <session-factory> <property name=”hibernate.connection.driver_class”>com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name=”current_session_context_class”>thread</property> <property name=”hibernate.connection.url”>jdbc:sqlserver:// JR01DB01:1446;databaseName=J2EEREFERENCEDB</property> <property name=”hibernate.connection.username”>J2eeAdmin</property> <property name=”hibernate.connection.password”>J2eeAdmin/property> <property name=”hibernate.connection.pool_size”>10</property> <property name=”show_sql”>true</property> <property name=”dialect”>org.hibernate.dialect.SQLServerDialect</property> <mapping resource=”employee.hbm.xml”/> </session-factory> </hibernate-configuration> |
In the above configuration file:
Driver class : In our example I have used SQLServer driver. Which you can edit with your database driver.
Connection URL : It is specific to your DB .
Username :Mention your DB user name
Password : Mention your database password.
Dialect : This tells the hibernate what is the dialect , in our example we use SQLServerDialect.
Mapping resource :This property defines the mapping tables. You can use any number of mapping resources.
Object Relational Mapping
Lets see how we can map the Employees Object to the Employees table.There are two ways we can map the table and an object
1) Hibernate mapping file
2) Annotation class
Hibernate mapping file name should be in XXX.hbm.xml format.In the below example file employee.hbm.xml is used to map Employee Object to the Employee table in the database.
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 36 37 38 39 40 |
public class Employee { private int emp_id; private String firstName; private String lastName; private String email; public String getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_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; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
Here is the format for employee.hbm.xml:
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>
<hibernate-mapping>
<class name=”Employee” table=”EMPLOYEES”>
<id name=”emp_id” column=”Emp_Id” type=”int”>
<generator class=”increment”/>
</id>
<property name=”firstName”>
<column name=”FIRSTNAME” />
</property>
<property name=”lastName”>
<column name=”LASTNAME”/>
</property>
<property name=”email”>
<column name=”EMAIL”/>
</property>
</class>
</hibernate-mapping>
Here we specify the class and table to be mapped to like below:
<class name=”Employee” table=”EMPLOYEES”>
Every class will have an ID , an unique value which helps to identify a column. In our example above ,we have mentioned ID generation strategy as increment. Hibernate will generate unique id by incrementing the current id +1
Developing Code to Test Hibernate
Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file. Then the save method on session object is used to save the contact information to the database:
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 |
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class FirstHibernate { public static void main(String[] args) { Session session = null; try{ // This step will read hibernate.cfg.xml and create the session factory SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session =sessionFactory.openSession(); System.out.println("Inserting Record"); Empployee emp= new Empployee(); emp.setFirstName("abc"); emp.setLastName("xy"); emp.setEmail "abc@209.97.166.197"); session.save(emp); System.out.println("Done"); }catch(Exception e){ System.out.println(e.getMessage()); finally{ session.flush(); session.close(); } } } |
Leave a Reply