Recruitment
Viettel IDC

How to Connect a Database to Java – A Complete JDBC and Hibernate Guide

Jul 23, 2026

Understanding how to connect a database to Java is one of the most fundamental skills every Java developer should master. Without a database connection, Java applications cannot store, retrieve, or process data efficiently.

In this guide, Viettel IDC explains two of the most widely used approaches for connecting Java to a database:

- JDBC (Java Database Connectivity) for executing SQL statements directly.

- Hibernate (ORM) for interacting with databases using object-oriented programming principles.

How to Connect a Database to Java – A Complete JDBC and Hibernate Guide

What Is JDBC?

JDBC (Java Database Connectivity) is the standard Java API for connecting to and interacting with relational databases. It provides a set of interfaces and classes that allow Java applications to execute SQL statements, retrieve query results through the ResultSet object, and manage database connections.

Using JDBC, Java applications can communicate with various relational database management systems (RDBMS), including MySQL, Oracle, PostgreSQL, and many others through their corresponding JDBC drivers.

The main JDBC components include:

- DriverManager – Manages and locates JDBC drivers.

- Connection – Represents a connection session with the database.

- Statement / PreparedStatement – Executes SQL queries and updates.

- ResultSet – Stores the results returned from SQL queries.

- SQLException – Handles database-related exceptions.

JDBC is a core component of Java SE for database programming. When running a Java application, developers simply call the JDBC API without worrying about the underlying implementation.

For example, the following statement establishes a database connection:

DriverManager.getConnection(url, user, password);

What Is JDBC?

Preparing the JDBC Environment

Before connecting Java to a database, make sure your development environment is properly configured.

Step 1. Install the JDK

Install Java Development Kit (JDK) 8 or later to compile and run Java applications.

Step 2. Install MySQL

Install MySQL Server and create a database (for example, mydb) that your Java application will connect to.

Step 3. Add the JDBC Driver

Download MySQL Connector/J, the official JDBC driver for MySQL, and add it to your project.

If you're using Maven, include the following dependency in your pom.xml:

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>8.0.33</version>

</dependency>

If you're not using Maven, simply add the JAR file to your project's classpath.

Step 4. Configure Your IDE

Ensure your IDE (such as Eclipse or IntelliJ IDEA) recognizes the installed JDK and that the JAVA_HOME and PATH environment variables are correctly configured.

If you're compiling from the command line, verify that both javac and java commands work properly.

Once the JDK, database, and JDBC driver are ready, you can start writing Java code to connect to your database.

How to Connect a Database to Java Using JDBC

Step 1. Load the JDBC Driver

Load the MySQL JDBC driver into your application using either:

Class.forName("com.mysql.cj.jdbc.Driver");

or

DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

Step 2. Establish a Database Connection

Define the connection URL in the following format:

jdbc:mysql://<host>:<port>/<database>

Then create a Connection object:

String url = "jdbc:mysql://localhost:3306/mydb";

 

Connection conn = DriverManager.getConnection(url, "root", "");

Step 3. Create a Statement

Use the Connection object to create a Statement or PreparedStatement for executing SQL commands.

Statement st = conn.createStatement();

Step 4. Execute SQL Statements

Send SQL commands through the Statement object.

- Use executeQuery() for SELECT statements.

- Use executeUpdate() for INSERT, UPDATE, and DELETE statements.

Example:

String sqlInsert = "INSERT INTO user(username, password) VALUES('gpcoder','123')";

 

int rows = st.executeUpdate(sqlInsert);

 

System.out.println("Rows inserted: " + rows);

Step 5. Process Query Results

For SELECT statements, iterate through the ResultSet to retrieve data.

ResultSet rs = st.executeQuery("SELECT * FROM users");

 

while (rs.next()) {

 

    int id = rs.getInt("id");

 

    String name = rs.getString("username");

 

    System.out.println(id + " - " + name);

 

}

For INSERT, UPDATE, or DELETE operations, the returned integer indicates how many rows were affected.

Step 6. Close Connections and Resources

After completing database operations, close the Statement and Connection objects to release system resources.

st.close();

 

conn.close();

For better resource management, use a try-with-resources statement or close them inside a finally block.

How to Connect a Database to Java Using Hibernate (ORM)

Besides JDBC, Java applications can also interact with databases using Hibernate, one of the most popular Object-Relational Mapping (ORM) frameworks.

Hibernate maps Java objects (POJOs) directly to database tables, allowing developers to perform database operations without writing large amounts of JDBC code manually.

Step 1. Create a Project and Add Dependencies

Create a Java project (typically using Maven or Gradle) and include:

- hibernate-core

- mysql-connector-java (or another JDBC driver)

Step 2. Define Entity Classes

Create Java POJO classes and annotate them using Hibernate annotations such as:

- @Entity

- @Table

- @Id

These annotations map Java classes to database tables.

How to Connect a Database to Java Using Hibernate (ORM) - Step 2

Step 3. Configure Hibernate

Create a configuration file such as:

- hibernate.cfg.xml

- application.properties

Configure:

- Database URL

- Username

- Password

- JDBC Driver

- SQL Dialect

- Hibernate properties

Step 4. Initialize SessionFactory and Session

Create a SessionFactory from the configuration, then open a Session to begin database transactions.

Example:

Configuration cfg = new Configuration().configure("hibernate.cfg.xml");

 

SessionFactory factory = cfg.buildSessionFactory();

 

Session session = factory.openSession();

How to Connect a Database to Java Using Hibernate (ORM) - Step 4

Step 5. Perform CRUD Operations

Use the Session object to:

- Insert data

- Update records

- Delete records

- Query objects

Hibernate automatically converts these operations into SQL statements.

Step 6. Commit Changes

Use the Session object to save or retrieve data.

Examples include:

- session.save(entity)

- session.update(entity)

- session.delete(entity)

- session.createQuery("FROM Role").list()

Finally, commit the transaction:

session.getTransaction().commit();

FAQs About Connecting Java to a Database

1. When Should You Use JDBC Instead of Hibernate?

JDBC is a better choice when:

- The project is relatively small.

- There are only a few database tables.

- You need full control over SQL statements.

- Maximum performance is required.

Hibernate is more suitable when:

- The project is medium or large.

- There are many database entities.

- Long-term maintenance is important.

- Faster development and object-oriented programming are priorities.

2. How Do I Fix the "Cannot Load JDBC Driver" Error?

This error usually occurs because the required JDBC driver is missing from your project.

To resolve it:

- Verify your Maven or Gradle dependencies.

- Ensure the mysql-connector-java (or your database's JDBC driver) is included in your project's classpath.

- Confirm that the correct driver class name is being used.

3. Why Do I Get the "Access Denied for User" Error?

This error typically means either:

- The username or password is incorrect.

- The database user does not have sufficient privileges.

Verify your login credentials and ensure the user has the necessary permissions, such as:

- CONNECT

- SELECT

- INSERT

- UPDATE

For MySQL, you can grant permissions using:

GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';

 

FLUSH PRIVILEGES;

Conclusion

You now understand two common ways to connect a database to Java: JDBC and Hibernate.

JDBC is ideal for direct SQL execution, lightweight applications, and situations where developers require complete control over database interactions.

Hibernate, on the other hand, significantly reduces boilerplate code, simplifies maintenance, and accelerates development by automatically mapping Java objects to database tables through ORM.

Regardless of which approach you choose, a reliable, secure, and scalable database infrastructure is essential for building enterprise-grade Java applications.

If you're planning to deploy mission-critical systems, consider Viettel IDC Database Service, a managed database solution that helps organizations optimize database performance, ensure high availability, monitor systems 24/7, and simplify database administration.

For more information or expert consultation, contact Viettel IDC through the following channels:

- Hotline: 1800 8088 (Toll-free)

- Facebook: https://www.facebook.com/viettelidc

- Website: https://viettelidc.com.vn/en/home

 

Comment ()

Login | Sign Up
to send comment
Your comment will be reviewed before being posted.
Your comment will be reviewed before being posted.
Your comment will be reviewed before being posted.
Read more

Related news

27/08/2026

Relational Algebra in Databases: Understanding Database Operations

Relational algebra in databases is defined as a procedural query language. In this model, data retrieval does not occur randomly but is carried out through a structured and logical system of operators.

27/08/2026

What Is a Primary Key in a Database? Understanding the Difference Between Primary Keys and Foreign Keys

A Primary Key is a fundamental element used to uniquely identify each record in a database. It not only ensures data integrity but also serves as a foundation for establishing strong relationships between tables.

27/08/2026

What Is a Foreign Key in a Database? A Complete Guide to Foreign Keys in SQL

A foreign key is a fundamental concept in relational database management systems. It acts as a bridge that establishes logical and reliable relationships between different data tables.

27/08/2026

What Is a Database Schema? Concepts, Types, and Importance

A Database Schema can be compared to an architectural blueprint for your data house. It defines the entire structure and organization of information within a database.

27/08/2026

What Is an ODS? Understanding Operational Data Stores and Comparing ODS vs. Data Warehouses

To gain a comprehensive, real-time view of their operations, businesses need the ability to instantly access data directly related to ongoing business activities. An Operational Data Store (ODS) makes this possible.

27/08/2026

What Is Data Synchronization? Its Importance in the Digital Era

In today’s business environment, data synchronization is a key solution for automating processes and ensuring that information remains consistent, accurate, and unified across the entire system, while minimizing the risk of human error.

27/08/2026

What Is Kubernetes Deployment? Understanding Application Lifecycle Management in Kubernetes

Deploying applications in a containerized environment involves more than simply running an individual container; it requires a more comprehensive management mechanism. Kubernetes addresses this need with Deployment, a tool that automatically manages the entire application lifecycle, from deployment and updates to rollbacks.

27/08/2026

What Is a Kubernetes Cluster? Understanding Its Architecture and How It Works in Kubernetes

As businesses transition to microservices and containerization, Kubernetes has become a leading platform for container orchestration. To operate reliably and manage large volumes of workloads, Kubernetes relies on a core architecture known as the Kubernetes Cluster.

27/08/2026

What Is a Kubernetes Pod? Architecture, How It Works, and a Detailed Guide to Pod Management

Kubernetes is a core platform for running containers at scale, and a Pod is the smallest unit in its architecture. Instead of managing containers directly, Kubernetes uses Pods as an abstraction layer that groups one or more containers running together.

27/08/2026

What Is Kubernetes Ingress? How It Works, Architecture, and a Detailed Deployment Guide

In a Kubernetes environment, exposing applications to the outside world is always one of the most important steps. This is why Kubernetes Ingress has become an optimal solution for managing traffic entering a cluster in a flexible, secure, and cost-effective manner.