Hibernate Tutorial JDBC vs Hibernate

Hibernate Tutorial JDBC vs Hibernate

One regular answer from a budding programmer is it is very difficult to understand Hibernate, Spring and Struts. Is it the technology (framework) like that? Does tutorials do not simplify the learning? I admit that both. The concept of way2java.com from the beginning is "simplifying the complexity". I generally avoid much of technology buzz words (I give at the end after learning the subject) which confuses a novice. Please pass your valuable comments how far I am succeeded to make Hibernate easy to understand and practice.

Of course, I too admit that, at the very beginning of learning Hibernate, everyone says it is "a very round about process to insert a record". But if you go a little far, you admit Hibernate is a boon for database connectivity. Let us go into the tutorial part.

What is Hibernate?

Hibernate is a powerful and high-performance ORM service. ORM is an acronym for "Object-relational Mapping", just as anyone immediately expresses. It is a very confusing definition for a fresher trying to learn Hibernate. At an outset, it is simply storing a Java object in a (relational) database. When stored, Hibernate automatically maps (places) and stores each instance variable value of a Java object in a database column. For example, an Employee object emp has three properties (instance variables) like emp.id, emp.name and emp.salary. When the object emp is stored in the database, Hibernate stores these variables values in the columns EMPID, EMPNAME and EMPSAL of a database table. This reduces the code of JDBC to a maximum extent (I feel it is 90% which you also accepts when you complete doing with Hibernate) which a programmer is most accustomed earlier. Java variables vs table columns mapping is done in an XML file (like web.xml, incase of servlets, where an alias name is mapped to the actual servlet).

Now let us talk with some technical buzzwords. Hibernate is object/relational persistence for Java and .NET technologies. Here, persistence means writing Java object to a permanent storage and making it to live (stay) long. Always persistence storage comes with writing to a hard disk like to a text file or a RDBMS table. Remember DS like an ArrayList or Vector gives a temporary storage (available to program until program terminates. Once the program execution is over, the data is lost and when you restart the same program, the data is not available) of data as the data is written to the RAM. Object/relational means storing or writing a Java object to a database (to be more precisely, relational database) like Oracle. Storing the variables of an object is known as storing the state of the object or persisting the object.

Hibernate is an open source code that can be freely downloaded from www.hibernate.org and used. Hibernate comes with three major versions – Hibernate 1.0, Hibernate 2.0 and Hibernate 3.0.

ORM is a supplement to JDBC and not a replacement. Infact, Hibernate internally uses JDBC. The aim of ORM is to reduce the writing of number of lines of DB programming code in Java.

Hibernate Architecture

Hibernate Tutorial JDBC vs Hibernate

Hibernate uses JDBC internally to insert a Java object into database. The main objects of Hibernate used in coding are Configuration, SessionFactory, Session and Transaction (and are explained in To insert a Record). The insertion of an object in database is known as persisting (literal meaning: preserving) a Java object.

Let us summarize the strengths of Hibernate briefly. Elaborate explanation will be available in respective topics.

JDBC vs Hibernate – Features of Hibernate (advantages of Hibernate over JDBC)

1. Transparent Persistence

It is a very complex task to write an object of an Object-Oriented programming language to a relational database with JDBC as there will be a mismatch between the data types (say, int) of a Java class and column types (say, number) of a database, and moreover, column types vary with each database. Hibernate takes care of this transparently depending on the database used (internally) without any botheration to the programmer.

Writing a Java object to a database and reading back is known as transparent persistence. Transparent means unknown to the programmer, to say, the internal implementation is unknown (for example, the accelerator or carburetor mechanism of a motor cycle is transparent to the rider). In JDBC, the programmer should take care of this manually with heavy lines of code.

To put it in another way:

What is happening internally to store a Java object in a table is completely transparent (not known or abstracted) to the programmer. Moreover

  1. How Java types like int and String are converted into database specific number and varchar2 are not known.
  2. How a Java object is mapped to a database table is not known to the programmer.
  3. What SQL query is used by the Hibernate is not known (of course, this can be known with extra line of code with the option show_aql).
  4. Programmer is not aware of the internal mechanism of maintaining the transactions, catches and fetches etc.

All the above transparent mechanism amounts to less JDBC code to the programmer.

2. Object relation management (Class – Class mapping)

Imagine there are two Java classes Student and Address with database tables school and addressbook. The primary key of school is a foreign key in addressbook. When a Student object is inserted in school table, automatically the address should also be inserted in addressbook table. When a Student record is deleted, its corresponding address in the addressbook table should also be deleted and so also for updations.

3. Auto schema/Table generation

When a Java object is tried to save to a database table, if the table does not exist, Hibernate creates a new table with appropriate types (specific to that database) and inserts the object. In Hibernate, inserting object means writing each variable of the Java object to each column of a table. That is, every Java object corresponds to one record in a database table.

4. Automatic Primary key generations

Hibernate has its own style of primary key generation for the records inserted without depending on the database native algorithm. Hibernate comes with its own data types (which are independent of any database). If required, programmer can suggest Hibernate to depend on the native database style or any sequence algorithm etc.

5. Support for Query Language (database independent queries)

JDBC uses SQL (Structured Query Language) which may vary with the database. Programmer should write an effective way of query, keeping in mind of the performance (like by decreasing the number of database hits to execute the query). Even though, Hibernate supports native SQL, it comes with its own query language known as HQL (Hibernate Query Language) which is independent of any database. HQL syntax is similar to SQL syntax and supports polymorphic queries. To say, HQL gives database independent code (SQL is database dependent code). Hibernate Query Language permits to write a query on class objects.

6. Maintenance Cost

JDBC programmer should write a lot of code to create Java persistent objects out of the Resultset object, if required. He may be required to write "emp.ename = res.getString(“empname”)" etc. where emp is an object of Employee class with variable ename. That is, the programmer should map manually himself the variables with database columns. Hibernate does this implicitly. It lessens the programmer code and this cuts short the development time and also maintenance cost.

7. Connection pooling

Hibernate supports connection pooling to increase the performance of database access (hits). Hibernate comes with three styles of pooling – apache dbcp, proxool and C3P0.

8. Optimize Performance (Caching)

If the client requires the same records again and again, Hibernate uses cache memory; places the records in cache and gives to the client. Cache is nothing but retention (storing or accumulating) of data. Hibernate comes with Hibernate Dual Layer Caching Architecture (HDLCA). Caching is transparent to client and increases the performance. In JDBC, the programmer should hand code everything.

9. Supports Transactions

Hibernate comes with transaction facility. To look after, there comes Transaction class. Using Transaction class, a programmer can begin or commit or rollback a transaction.

10. Criteria and Criterion/Conditions and Condition

Hibernate comes with Criteria class to use with HQL. Criteria impose restrictions (constraints) on a database query.

11. Open Source Code

Hibernate is absolutely free either for trial use or commercial use. It is available under LGPL (Lesser General Public License). Hibernate can be freely distributed and customized for both development and production deployments.

12. Automatic Versioning and Time Stamping

Versioning is a feature of a database where the user is guaranteed of changes done by him are not rolled back by another intentionally or unintentionally. Automatic versioning is a technique of assuring data integrity. Hibernate allows the programmer to specify the version field. On this field, the Hibernate updates the table each time relational tuple is modified through a Java class object. A row in a table is called tuple of the relation. When one user does an update operation, the other is not allowed. JDBC does not come with implicit check of updation of data.

13. Enterprise Reliability and Scalability

Hibernate can scale database hits from few hundreds of in-house Intranet to enterprise mission critical operations with lakhs of hits. In JDBC it is very difficult.

Disadvantages of Hibernate

  1. For a novice, learning takes a long time due to lot of features Hibernate supports.
  2. Hibernate increases complexity to enter data in a database with all mapping XML files etc. When database does not change frequently, I feel, JDBC is the best choice.
  3. In Web (Internet) environment, Hibernate API support is not adequate.
  4. Hibernate does not allow to store or save two objects in a database with a single query.

These disadvantages are minimal and need not be bothered to the advantages it gives.

Other ORM frameworks

1. Hibernate 2. iBatis 3. TopLink 4. EclipseLink 5. JDO 6. Open JPA

11 thoughts on “Hibernate Tutorial JDBC vs Hibernate

  1. brad

    I dont agree with you ..If you know what is hibernate really you never recommend to work with JDBC
    With in the industry almost jdbc vanished out.

    Jdbc is never recommend to use persistence layer because
    1)if you use jdbc your business logic is tightly coupled with underline data base,if any change happen in data base your business logic will not work again you need to modify in every where in your business logic its so complicated
    2)jdbc will not provide boiler plate logic
    boiler plate logic is a piece of code it is required for all the classes in jdbc logic
    suppose i need a execute query for this i have to write
    load the driver
    establish the connection
    execute query this piece of logic is required for all the developers with in the project ..if you jdbc every developer has to write this logic its indicated duplicate data across your project.

    there are many drawbacks with jdbc i explainde only 2 problems i will give plenty of drawbacks

    BE CAREFUL BEFORE POSTING ARTICLE.

  2. binaya

    This is really nice each and every parts describe very well with example.

    But at last i did not get this
    “Hibernate does not allow to store or save two objects in a database with a single query.”

    So can u please give some brief explanation for this.

    Thanks in Advance

  3. saravanamanikandan

    sir, is this correct definition about dbms(no relationship maintained) and rdbms(based on relationship of different tables)… or other than that is there any differences. plz answer me and give ex db for each type.

Leave a Reply

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