Page 1 of 2 12 LastLast
Results 1 to 20 of 21
Like Tree1Likes

Thread: Advantage Hibernate over JDBC

  1. #1
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    71
    Rep Power
    0

    Default Advantage Hibernate over JDBC

    The question is simple. Where is the advantage when using Hibernate over JDBC? Infact I see JDBC code is more systematic and clearer than Hibernate code. How does having Hibernate less amount of code than JDBC?

    JDBC does not need even POJO classes. So where is the advantage?

    I have posted samples of Hibernate and JDBC code. Thanks in advance for your help.

    JDBC code:
    Java Code:
    import java.sql.*;
    
    public class JDBCExample {
       // JDBC driver name and database URL
       static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
       static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
    
       //  Database credentials
       static final String USER = "username";
       static final String PASS = "password";
       
       public static void main(String[] args) {
       Connection conn = null;
       Statement stmt = null;
       try{
          //STEP 2: Register JDBC driver
          Class.forName("com.mysql.jdbc.Driver");
    
          //STEP 3: Open a connection
          System.out.println("Connecting to a selected database...");
          conn = DriverManager.getConnection(DB_URL, USER, PASS);
          System.out.println("Connected database successfully...");
          
          //STEP 4: Execute a query
          System.out.println("Inserting records into the table...");
          stmt = conn.createStatement();
          
          String sql = "INSERT INTO Registration " +
                       "VALUES (100, 'Zara', 'Ali', 18)";
          stmt.executeUpdate(sql);
          sql = "INSERT INTO Registration " +
                       "VALUES (101, 'Mahnaz', 'Fatma', 25)";
          stmt.executeUpdate(sql);
          sql = "INSERT INTO Registration " +
                       "VALUES (102, 'Zaid', 'Khan', 30)";
          stmt.executeUpdate(sql);
          sql = "INSERT INTO Registration " +
                       "VALUES(103, 'Sumit', 'Mittal', 28)";
          stmt.executeUpdate(sql);
          System.out.println("Inserted records into the table...");
    
       }catch(SQLException se){
          //Handle errors for JDBC
          se.printStackTrace();
       }catch(Exception e){
          //Handle errors for Class.forName
          e.printStackTrace();
       }finally{
          //finally block used to close resources
          try{
             if(stmt!=null)
                conn.close();
          }catch(SQLException se){
          }// do nothing
          try{
             if(conn!=null)
                conn.close();
          }catch(SQLException se){
             se.printStackTrace();
          }//end finally try
       }//end try
       System.out.println("Goodbye!");
    }//end main
    }//end JDBCExample
    Hibernate Example:
    Java Code:
    import java.util.List; 
    import java.util.Date;
    import java.util.Iterator; 
     
    import org.hibernate.HibernateException; 
    import org.hibernate.Session; 
    import org.hibernate.Transaction;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class ManageEmployee {
       private static SessionFactory factory; 
       public static void main(String[] args) {
          try{
             factory = new Configuration().configure().buildSessionFactory();
          }catch (Throwable ex) { 
             System.err.println("Failed to create sessionFactory object." + ex);
             throw new ExceptionInInitializerError(ex); 
          }
          ManageEmployee ME = new ManageEmployee();
    
          /* Add few employee records in database */
          Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
          Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
          Integer empID3 = ME.addEmployee("John", "Paul", 10000);
    
          /* List down all the employees */
          ME.listEmployees();
    
          /* Update employee's records */
          ME.updateEmployee(empID1, 5000);
    
          /* Delete an employee from the database */
          ME.deleteEmployee(empID2);
    
          /* List down new list of the employees */
          ME.listEmployees();
       }
       /* Method to CREATE an employee in the database */
       public Integer addEmployee(String fname, String lname, int salary){
          Session session = factory.openSession();
          Transaction tx = null;
          Integer employeeID = null;
          try{
             tx = session.beginTransaction();
             Employee employee = new Employee(fname, lname, salary);
             employeeID = (Integer) session.save(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
          return employeeID;
       }
       /* Method to  READ all the employees */
       public void listEmployees( ){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             List employees = session.createQuery("FROM Employee").list(); 
             for (Iterator iterator = 
                               employees.iterator(); iterator.hasNext();){
                Employee employee = (Employee) iterator.next(); 
                System.out.print("First Name: " + employee.getFirstName()); 
                System.out.print("  Last Name: " + employee.getLastName()); 
                System.out.println("  Salary: " + employee.getSalary()); 
             }
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
       /* Method to UPDATE salary for an employee */
       public void updateEmployee(Integer EmployeeID, int salary ){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             Employee employee = 
                        (Employee)session.get(Employee.class, EmployeeID); 
             employee.setSalary( salary );
    		 session.update(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
       /* Method to DELETE an employee from the records */
       public void deleteEmployee(Integer EmployeeID){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             Employee employee = 
                       (Employee)session.get(Employee.class, EmployeeID); 
             session.delete(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
    }

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Advantage Hibernate over JDBC

    Try working with a model that is a little more complex, perhaps then you'll see it. Talk to me again when you have a hundred tables.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Advantage Hibernate over JDBC

    Not just a model that's "a little more complex".
    I would say "try with a model", for the JDBC one. There's no model there currently.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    71
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    Ok. Assume there are 1000's of tables. But still the mapping is done in the XML file.

    Here's a quote:
    With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Src: Hibernate Vs. JDBC ( A comparison)

    JDBC code:
    Java Code:
    import java.sql.*;
    
    public class FirstExample {
       // JDBC driver name and database URL
       static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
       static final String DB_URL = "jdbc:mysql://localhost/EMP";
    
       //  Database credentials
       static final String USER = "root";
       static final String PASS = "";
       
       public static void main(String[] args) {
       Connection conn = null;
       Statement stmt = null;
       try{
          //STEP 2: Register JDBC driver
          Class.forName("com.mysql.jdbc.Driver");
    
          //STEP 3: Open a connection
          System.out.println("Connecting to database...");
          conn = DriverManager.getConnection(DB_URL,USER,PASS);
    
          //STEP 4: Execute a query
          System.out.println("Creating statement...");
          stmt = conn.createStatement();
          String sql;
          sql = "SELECT id, first, last, age FROM Employees";
          ResultSet rs = stmt.executeQuery(sql);
    
          //STEP 5: Extract data from result set
          while(rs.next()){
             //Retrieve by column name
             int id  = rs.getInt("id");
             int age = rs.getInt("age");
             String first = rs.getString("first");
             String last = rs.getString("last");
    
             //Display values
             System.out.print("ID: " + id);
             System.out.print(", Age: " + age);
             System.out.print(", First: " + first);
             System.out.println(", Last: " + last);
          }
          //STEP 6: Clean-up environment
          rs.close();
          stmt.close();
          conn.close();
       }catch(SQLException se){
          //Handle errors for JDBC
          se.printStackTrace();
       }catch(Exception e){
          //Handle errors for Class.forName
          e.printStackTrace();
       }finally{
          //finally block used to close resources
          try{
             if(stmt!=null)
                stmt.close();
          }catch(SQLException se2){
          }// nothing we can do
          try{
             if(conn!=null)
                conn.close();
          }catch(SQLException se){
             se.printStackTrace();
          }//end finally try
       }//end try
       System.out.println("Goodbye!");
    }//end main
    }//end FirstExample
    In the JDBC code I dont see any mapping for the id, first, last and age attributes. But still the above code works. Either the statement is wrong or I am missing something.

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Advantage Hibernate over JDBC

    Quote Originally Posted by jmohandos304 View Post
    Ok. Assume there are 1000's of tables. But still the mapping is done in the XML file.
    In stead of just plucking outdated information from random sources on the net, try reading the up-to-date Hibernate documentation.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    I mean to say by using Hibernate we are not getting rid of the mapping but instead mention it in the xml mapping document. So we are not free of the mapping just because we use hibernate.

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Advantage Hibernate over JDBC

    Do I need to repeat myself? Switching user accounts changes nothing - read the documentation and actually inform yourself, because right now you are making statements based on you being incredibly misinformed.

    How many more dupe accounts do you have anyway? I want to put them all on my ignore list.
    Last edited by gimbal2; 05-13-2014 at 12:43 PM.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    Here is the link to the official documentation.

    http://docs.jboss.org/hibernate/orm/..._reference.pdf

    It does not mention what is the advantage of using Hibernate over JDBC.

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Advantage Hibernate over JDBC

    Quote Originally Posted by jmohandos304 View Post
    In the JDBC code I dont see any mapping for the id, first, last and age attributes. But still the above code works. Either the statement is wrong or I am missing something.
    That whole chunk of code inside the rx.next loop is the mapping.

    Quote Originally Posted by suhaas_mohandos View Post
    Here is the link to the official documentation.

    http://docs.jboss.org/hibernate/orm/..._reference.pdf

    It does not mention what is the advantage of using Hibernate over JDBC.
    Look up relationships, lazy loading, transaction handling, caching, I could go on.

    If you can't see the advantages then that is simply because you have never had to use pure JDBC in a production environment.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    Yes those are advantages, but I am asking about code reduction advantage in Hibernate over JDBC.

    Hibernate has a mapping document called <classname>.hbm.xml which has the mapping of properties of class to fields in the table.

    On the other hand JDBC does not require any such kind of mapping.

    Please let me know the advantage from the point of view that I am asking.

  11. #11
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    That whole chunk of code inside the rx.next loop is the mapping.

    Ok.Agree.

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Advantage Hibernate over JDBC

    [QUOTE=suhaas_mohandos;382791]Yes those are advantages, but I am asking about code reduction advantage in Hibernate over JDBC.

    Hibernate has a mapping document called <classname>.hbm.xml which has the mapping of properties of class to fields in the table.
    [/code]

    I haven't got one of those in my current project.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    448
    Rep Power
    1

    Default Re: Advantage Hibernate over JDBC

    Tolls: so instead of mapping files you are using JPA annotations?
    (I am just checking if I understood the concepts correctly)

    suhaas: why don't you write a really simple example? But be sure that you write a complete example. Just take anything yoy like to have organized.
    - now you write the class itself. That should be a POJO for different reasons.
    - now you write an adapter class for CRUD operations
    Really simple and easy and you got a working basis for your business object.

    Now do the same with the hibernate framework.

    Now compare it. And that is really simple. Switch the database or implement caching or .....

    But yes: to insert a few entries or read a single table hibernation is not the tool to choose. But when you build an application then you want to have entities that you can work with.

    Konrad

  14. #14
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    why don't you write a really simple example? But be sure that you write a complete example

    Somebody said in the forum that it should have many tables.

  15. #15
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    Steps in JDBC
    1. Register JDBC driver
    2. Open connection
    3. Execute Query

    Steps in Hibernate
    1. Create Factory object
    2. Open session
    3. Create Transaction
    4. Perform operation

    Looking at the above how can one say Hibernate is better compared to JDBC?

  16. #16
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    448
    Rep Power
    1

    Default Re: Advantage Hibernate over JDBC

    Hmm. Why do you use JDBC or Hibernate? Why don't you simply write a Hello World application?

    Steps in HelloWorld application:
    1. Print "Hello World!"

    That is much much simpler!

    So looking at the above: How can one say JDBC is better compared to Hello World?

    What I tried to tell you is quite simple:
    - Your JDBC example is just doing one simple query.
    - With hibernate you get a solution that you can use to create, read, update and delete objects from the database. If you want to get the same in JDBC, then you have to write much more code.

    If you want to write a simple query: Yes, take the JDBC approach. There is no reason to use hibernate if you just want to execute a simple sql query.
    (As nobody would use JDBC if the target is a simple hello world application!)

    But please understand that real application (bigger than simple hello world application) require much much more. When you have to build an application which has data inside a database, then you need tested code that handles everything.
    Imagine you write a software that manages a company. So one of the tables is employees.
    So you need a class "employee". And now you need code that
    - stores a new employee inside the database.
    - reads an employee from the database.
    - saves changes of an employee to the database.
    - removes an employee from the database (Ok, maybe not. This depends on the business logic required. you might have a field "fired" or so.)

    So you write code for all these steps and then test them. And when you change something, you have to do the same change in multiple locations (e.g. instead of Name you split it up to Forename and Surname). So even if the code is not really double it is some kind of double code. And it is a lot of typing...

    So hibernation is great: You just build the pojo and the binding and you are done. maybe you even have tools that do that for you! And doing changes is quite easy, too. Just the POJO must be changed and the binding.

    But that is just one possibility. Nobody says that it is required. Nobody says that JDBC is wrong. And there are even cases where JDBC is better.
    - simple queries are such a case.
    - Bulk inserts, that are a lot of simple queries, are an important point.

    Konrad
    Tolls likes this.

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Advantage Hibernate over JDBC

    Quote Originally Posted by kneitzel View Post
    Tolls: so instead of mapping files you are using JPA annotations?
    (I am just checking if I understood the concepts correctly)
    Yep.
    And I did it to highlight some of what I think gimbal was talking about.
    Talking about needing xml files for mapping is missing the point. As is simply referring to querying a table and presuming that represents an application (nice analogy with HelloWorld, by the way).
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  18. #18
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    Quote Originally Posted by Tolls View Post
    Yep.
    And I did it to highlight some of what I think gimbal was talking about.
    Talking about needing xml files for mapping is missing the point. As is simply referring to querying a table and presuming that represents an application (nice analogy with HelloWorld, by the way).
    Ok. Forget about mapping. What about the points I mentioned in post 15?

    I dont know how much time the points mentioned in post 15 take. But if you claim to understand the advantage of Hibernate over JDBC then let me know how it is advantageous?
    Last edited by suhaas_mohandos; 05-14-2014 at 10:56 AM.

  19. #19
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    448
    Rep Power
    1

    Default Re: Advantage Hibernate over JDBC

    Hi,

    I just don't know what to reply any more. I think we said everything and all we could do right now is repeating ourself.

    As I said: If all you want to do is a simple query and just that query, then JDBC is great. Esp. if your query is really simple and you do not care about transactions. And you simply do not care about having entities with a solid codebase to create, read, update and delete (CRUD) them.

    Please read carefully about database adapters. What code is required for it. This is nothing that I will post here. Just sit down and create your own example. Just do it. Stop asking about multiple tables or so. Just start with the simplest example:
    - Create a simple table e.g. "employees" with fields "Id", "Name", "Street", "City"
    - Create a plain Class Employee with Id, Name, Street, City as fields and the proper setter/getter.
    - Now write a class EmployeeAdapter with functions to
    - find an employee by id
    - find an employee by name
    - list all employees
    - insert a new employee
    - update an existing employee
    - delete an employee
    ==> Now you got a Data Adapter using JDBC.

    Now you can check the same with hibernation. Now a comparison is ok, because you have something that is more or less doing the same.
    But this "more or less the same" is even completely wrong: We still left a lot of things out:
    - Just change the underlying database. The hibernation framework takes care of that!
    - Just get more complex databases - then you suddenly need transactions and such things.

    If you read about hibernation, then you will even find some kind of rules when you should not use it. Bulk inserts are such a case.
    So nobody says that hibernation is better than JDBC. It always depends on what you want to do. If you simply want to do a simple query: Stay on JDBC.

    And please: Start with JDBC and build a data adapter yourself. It might help you to understand what it going on. I really hate if people use black boxes and have no idea what is going on. It is like driving a car without any knowledge what is going on. And I guarantee that you run into trouble sooner or later and you will have no idea at all what is wrong. And if you did some real applications as I described then you will quickly see why other solutions might be useful.

    Or maybe you can check out the book "Pro Spring 3". In chapter 8 they describe the swing possibilities to support the developer. And they start with the old fashion JDBC and what code you have to write before they come to the possibilities of spring (which are based on other core technologies e.g. hibernation, JPA, ...).

    Maybe this helps a little bit.

    And if we really want to compare your 2 lists of JDBC and Hibernate: Even your list shows that hibernate is doing much more. You have transactions .... Maybe you should read more about transactions. If you are doing a business application you have to make sure that you do not corrupt the data. Business applications simply need more than just executing a simple query.

    Konrad

  20. #20
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Advantage Hibernate over JDBC

    - Just change the underlying database. The hibernation framework takes care of that!
    - Just get more complex databases - then you suddenly need transactions and such things.


    That helps!

Page 1 of 2 12 LastLast

Similar Threads

  1. advantage of using thread
    By simorgh in forum Threads and Synchronization
    Replies: 3
    Last Post: 02-18-2010, 05:53 AM
  2. How Hibernate is good rather than jdbc
    By sreehari556@gmail.com in forum Advanced Java
    Replies: 5
    Last Post: 12-17-2009, 08:41 AM
  3. Replies: 7
    Last Post: 09-16-2008, 06:20 PM
  4. Performance Hibernate against jdbc api
    By javadev in forum JDBC
    Replies: 2
    Last Post: 06-05-2008, 03:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •