Difference between ORM and JDBC in Java

1. Introduction

In Java, ORM (Object-Relational Mapping) and JDBC (Java Database Connectivity) are two different approaches for interacting with databases. ORM is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. JDBC is an API for connecting and executing SQL operations in a relational database.

2. Key Points

1. ORM allows you to work with databases using Java objects, without writing SQL queries explicitly.

2. JDBC requires you to write SQL queries directly in your Java code.

3. ORM provides a way to map between Java objects and database tables.

4. JDBC deals with database data at the column level, whereas ORM works with entire objects.

3. Differences

ORM JDBC
Abstracts the database access with objects. Directly manages the database access with SQL queries.
Objects are mapped to database tables. Works with database tables and columns directly.
Can automate schema creation and update. Requires manual schema creation and update.
Tends to be slower due to the additional abstraction layer. Tends to be faster as it involves direct SQL queries.

4. Example

// JDBC example (Assuming a `users` table exists in the database)

public class JdbcExample {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            // Step 1: Load the JDBC driver
            Class.forName("com.jdbc.Driver");

            // Step 2: Establish a connection
            connection = DriverManager.getConnection("jdbc:database_url", "username", "password");

            // Step 3: Create a statement
            Statement statement = connection.createStatement();

            // Step 4: Execute a query
            ResultSet resultSet = statement.executeQuery("SELECT * FROM users");

            // Step 5: Process the results
            while(resultSet.next()) {
                System.out.println("User: " + resultSet.getString("username"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Step 6: Close the connection
            if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
        }
    }
}

// ORM example (Assuming a `User` class is mapped to a `users` table)

public class OrmExample {
    public static void main(String[] args) {
        // Step 1: Obtain an ORM session
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        // Step 2: Retrieve all User objects
        List<User> users = session.createQuery("from User").list();

        // Step 3: Process the results
        for (User user : users) {
            System.out.println("User: " + user.getUsername());
        }

        // Step 4: Close the session
        session.getTransaction().commit();
        session.close();
    }
}

Output:

// Output from JdbcExample
User: alice
User: bob
// Output from OrmExample
User: alice
User: bob

Explanation:

1. The JdbcExample class directly uses JDBC to load a driver, establish a connection to the database, create a statement, execute an SQL query, process the results, and close the connection.

2. The OrmExample class uses an ORM framework to open a session, begin a transaction, query for User objects using HQL (Hibernate Query Language), process the list of User objects, and finally commit the transaction and close the session.

5. When to use?

- Use JDBC for fine-grained control over database operations and for performance-critical applications where speed is crucial.

- Use ORM when you prefer to work with Java objects, or when you want to abstract away the underlying SQL for ease of maintenance and development.

Comments