How to Connect a Database to Java – A Complete JDBC and Hibernate Guide
Jul 23, 2026Understanding 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.
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);
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.
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();
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
Featured news
Related news
Kubernetes vs Serverless? Which Is the Right Choice for Enterprise Architecture?
In the Cloud Native era, Kubernetes vs Serverless represents a classic clash between two philosophies: Maximum control or ultimate convenience? If Kubernetes can be considered the solid backbone for complex Microservices systems, Serverless is the speed-driven launchpad that helps optimize costs for enterprises. So, which one is the right fit for your architecture?
What Is Kubespray? A Production-Ready Kubernetes Deployment Solution for Enterprises
Kubernetes has revolutionized Container orchestration, providing an efficient and flexible solution for application deployment. However, manually setting up and maintaining a Kubernetes Cluster is often highly complex and can easily become overwhelming.
What Is Minikube? A Beginner’s Guide to Running Kubernetes
Do you want to start learning Kubernetes but are concerned about server rental costs or complicated configuration? Minikube is the perfect answer. So, what is Minikube, and how does this tool turn your laptop into a “pocket-sized” Kubernetes Cluster that you can use for completely free hands-on practice?
What Is a Helm Chart? The Most Effective Way to Manage Kubernetes Applications
Are you overwhelmed by having to manage dozens of separate YAML configuration files every time you deploy an application to Kubernetes? That’s when you need Helm Chart – a solution often described as the key to escaping configuration hell.
What Is a Service in Kubernetes? A Complete A-Z Guide to Service Types and Configuration
In the Kubernetes world, Pods have one defining characteristic: they are ephemeral. They are constantly created, terminated, and replaced. Each time this happens, a Pod’s IP address changes. This creates a challenging problem: How can A communicate with B if B’s IP address keeps changing? The answer is Kubernetes Service.
What Is a Namespace in Kubernetes? A Complete A-Z Guide to Creating and Managing Namespaces
A Kubernetes Cluster is like a huge office building. Without proper zoning, resource conflicts between departments (Dev, Test, Prod) are inevitable. Kubernetes Namespaces are the essential partitions that divide physical infrastructure into multiple Virtual Clusters, ensuring effective isolation and management.
Kubernetes Cost Optimization: Effective Cloud Cost Reduction Strategies for Businesses
Kubernetes enables businesses to deploy and operate containerized applications at scale with greater flexibility. However, this flexibility also comes with increasingly complex cost management challenges. Kubernetes cost optimization is not simply about cutting resources or shrinking the cluster.
What Is the Vertical Pod Autoscaler? Effectively Optimizing Pod Resources in Kubernetes
In Kubernetes, manually setting CPU and memory resources for Pods can easily lead to either resource shortages or infrastructure waste. Improper configuration can cause applications to slow down, experience OOMKilled errors, or prevent the cluster from fully utilizing its available capacity. The Vertical Pod Autoscaler provides a smarter approach by automatically recommending and adjusting resources based on actual usage.
What Is the Kubernetes Scheduler? How Kubernetes Decides Where Pods Run
In Kubernetes, a Pod does not automatically start running immediately after it is created. It first needs to be assigned to a suitable node within the cluster. This task is handled by the Kubernetes Scheduler, whose role is to determine where a Pod should run. The Scheduler helps allocate resources efficiently, maintain system stability, and optimize overall performance.
Kubernetes vs Docker: Understanding the Key Differences for Effective Container Deployment
During the application containerization process, many people who are new to DevOps often confuse Docker and Kubernetes as two tools with the same role, and some even believe that learning only one of them is sufficient. In reality, Docker and Kubernetes solve two completely different problems, but they are closely connected within modern deployment architectures.
Comment ()