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
Related news
When Should You Scale Up vs. Scale Out? A Guide to Choosing the Most Effective Approach
As IT systems evolve, particularly websites, web applications, and digital service platforms, scaling resources becomes almost inevitable. However, deciding how to scale is a challenge that leaves many businesses and technical teams uncertain.
Do You Need DevOps to Operate a Cloud Server? Insights from Real-World Implementations
In recent years, Cloud Server has become a popular infrastructure platform for almost every type of IT system, ranging from small business websites to large-scale applications. However, alongside the flexibility and scalability of cloud computing comes increasing operational complexity. Many organizations are asking: Do you need DevOps to operate a Cloud Server, or is a traditional IT team sufficient?
Can You Recover Data That Has Been Accidentally Deleted from the Cloud?
Can you recover data that has been accidentally deleted from the cloud? This is a common question among users today. Cloud storage services such as Dropbox, Google Drive, and Microsoft OneDrive all incorporate data protection mechanisms that temporarily retain deleted files for a certain period.
How Do Cloud Providers Protect User Data?
In the era of digital transformation, how cloud providers protect user data has become a major concern for both businesses and individuals. As more data is stored on cloud computing platforms, cloud providers must implement multiple layers of sophisticated security measures to ensure that data remains safe from cyberattacks, data breaches, and infrastructure failures.
Can You Run a Game Server on a Cloud Server? A Detailed Explanation
A Cloud Server is more than just a data storage solution. It can also be used to run games directly, host game servers, or support Cloud Gaming. Viettel IDC will help you understand the capabilities of Cloud Servers in the gaming industry and how to choose the right server configuration for your needs.
Is Cloud Server Suitable for Hosting a WordPress Website? A Detailed Explanation
WordPress is a popular website-building platform, but running a website reliably requires sufficiently powerful and flexible server infrastructure. This is why many businesses ask whether Cloud Server is suitable for hosting a WordPress website when choosing a hosting environment.
How to Improve Cloud Server Performance: Best Optimization Tips
How to improve Cloud Server performance is a common question among businesses running websites or applications on cloud computing platforms. If a server runs slowly or processes data inefficiently, the system may experience performance issues that affect speed and user experience.
What Is the Difference Between Cloud Storage and Cloud Server? A Detailed Comparison
What is the difference between Cloud Storage and Cloud Server? This is a common question among businesses starting to use cloud computing services. Although both are part of the cloud ecosystem, Cloud Storage and Cloud Server serve different purposes and functions in data storage and IT system operations.
What Is an Image Server? How It Works and Its Role in Website Infrastructure
An image server is a server specifically designed to store, process, and deliver images for websites or applications. By using dedicated image processing and delivery mechanisms, an image server helps improve page load speeds, reduce the workload on the main server, and enhance the user experience when accessing a system.
Can Data Be Exposed When Using a Cloud Server? A Detailed Explanation
Can data be exposed when using a Cloud Server? In practice, data can still be exposed if the system is misconfigured or has weak security. However, these risks can be effectively managed by choosing a reputable cloud service provider and implementing appropriate security measures.
Comment ()