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

20/11/2026

Data Center Asset Management: 8 Core Components and Best Practices

Discover the 8 core components of Data Center Asset Management, key lifecycle stages, and best practices to optimize infrastructure, reduce costs, and improve operational efficiency.

20/11/2026

What Is Data Center Automation? Benefits & 5 Steps to Implement

Discover what Data Center Automation is, its key benefits, practical applications, and five steps to automate data center operations effectively.

20/11/2026

What Is Data Center Change Management? 5 Key Steps

Learn what Change Management in a data center is, why it matters for uptime, and how a 5-step process helps minimize operational risks and service disruptions.

20/11/2026

What Is Cross Connect in a Data Center? Benefits & Uses

Learn what Cross Connect in a data center is, how it reduces latency, enhances security, and improves network reliability for enterprise connectivity.

20/11/2026

Can a Data Center Be Hacked? Risks and Security Measures

Can a data center be hacked? Explore common attack methods, security risks, potential consequences, and effective ways to protect data center infrastructure.

20/11/2026

What Is a Mantrap in a Data Center? Benefits & Security

Learn what a Data Center Mantrap is, how it works, and how it prevents tailgating, unauthorized access, equipment theft, and physical security threats.

20/11/2026

Data Center Overheating: Causes, Risks & Prevention Solutions

Discover the main causes and risks of Data Center overheating, its impact on IT infrastructure, and effective cooling solutions to prevent downtime and hardware failures.

20/11/2026

Active-Active vs. Active-Passive in Data Centers: Key Differences

Compare Active-Active vs. Active-Passive Data Center architectures, including their working principles, advantages, disadvantages, costs, RTO, RPO, and use cases.

20/11/2026

What Is a BCP? Understanding Its Role in Data Centers

Learn what a Business Continuity Plan (BCP) is, its key components, development process, and importance in ensuring Data Center availability and resilience.

20/11/2026

ISO 27001 in Data Centers: Benefits, Requirements & Certification

Learn what ISO 27001 means for Data Centers, how it strengthens information security, its key benefits, certification process, and implementation challenges.