? Understanding JDBC: Java Database Connectivity ?

? Understanding JDBC: Java Database Connectivity ?

Java Database Connectivity (JDBC) is an API that enables Java applications to interact with relational databases. It provides a standard interface for connecting to a database, executing queries, and retrieving results.

?? Key Components of JDBC

  1. ?? JDBC Driver: A software component that establishes a connection between Java applications and databases.
  2. ? Connection: Represents a session with the database.
  3. ?? Statement: Used to execute SQL queries.
  4. ?? ResultSet: Stores the results retrieved from a query execution.
  5. ?? PreparedStatement: A precompiled SQL statement that improves performance.
  6. ?? CallableStatement: Used for calling stored procedures.

? Steps to Use JDBC

1. ?? Load the JDBC Driver

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

2. ? Establish a Connection

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");        

3. ?? Create and Execute a Statement

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");        

4. ?? Process the Results

while (rs.next()) {
    System.out.println(rs.getString("name"));
}        

5. ?? Close the Connection

rs.close();
stmt.close();
con.close();        

?? Types of JDBC Drivers

  1. ?? JDBC-ODBC Bridge Driver (Type 1) - Uses ODBC driver; not commonly used now.
  2. ?? Native-API Driver (Type 2) - Uses database vendor-specific APIs.
  3. ?? Network Protocol Driver (Type 3) - Uses a middleware server for database communication.
  4. ?? Thin Driver (Type 4) - Pure Java driver, directly communicates with the database.

? When to Use JDBC in Spring Boot

? High Performance Requirements

JDBC allows direct interaction with the database without the overhead of an ORM like Hibernate.

?? Complex Queries and Stored Procedures

JDBC provides fine-grained control over query execution and result handling.

?? Lightweight Applications

Using JDBC can reduce dependency on heavier frameworks when basic CRUD operations are needed.

?? Legacy Systems

JDBC offers better compatibility when integrating with legacy databases.

?? Batch Processing

JDBC allows batch updates, improving performance for multiple queries.

?? Using JDBC in a Spring Boot Application

?? Step 1: Add Dependencies

Add these dependencies in pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>        

?? Step 2: Configure DataSource

Configure database properties in application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver        

?? Step 3: Use JdbcTemplate

Spring Boot provides JdbcTemplate, simplifying JDBC operations:

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserRepository {
    private final JdbcTemplate jdbcTemplate;

    public UserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> findAll() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, new UserRowMapper());
    }
}

class UserRowMapper implements RowMapper<User> {
    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        return new User(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
    }
}        

?? Step 4: Perform Database Operations

You can now call UserRepository.findAll() to retrieve data.

? Advantages of JDBC

  • ?? Platform-independent database connectivity.
  • ?? Supports various relational databases like MySQL, PostgreSQL, and Oracle.
  • ?? Efficient data retrieval and manipulation.
  • ? Works with Java EE frameworks like Hibernate and Spring Data.
  • ?? Spring Boot simplifies JDBC with built-in configurations.

?? Best Practices

  • ?? Use connection pooling for better performance.
  • ?? Always close database resources to prevent memory leaks.
  • ?? Prefer PreparedStatements to prevent SQL injection.
  • ?? Handle exceptions properly using try-with-resources.

JDBC remains an essential part of Java-based database applications, providing a flexible and reliable way to interact with relational databases. Spring Boot enhances JDBC usage by reducing configuration overhead and simplifying database interactions. ?

??t Tr??ng Thành

? Software Developer | Java Spring boot | Database | Studies Performance Tuning at Wecommit Vi?t Nam. Let's connect!

1 个月

Thank you, very informative! You helped me understand JDBC better.

回复
André Ramos

Senior Software Engineer | Java | Spring Boot | Micro Services | Fullstack Software Developer | Angular | AWS | TechLead

1 个月

Very informative! Thanks for sharing! ??

回复

要查看或添加评论,请登录

Ngo Tran Quoc Tuan (Liam)的更多文章

  • ?? JSON Web Token (JWT)

    ?? JSON Web Token (JWT)

    1. ?? Gi?i thi?u v? JWT JWT (JSON Web Token) là m?t chu?n m? (RFC 7519) cho phép truy?n th?ng tin m?t cách an toàn gi?a…

    1 条评论
  • ?? L?p trình h??ng ??i t??ng (OOP)

    ?? L?p trình h??ng ??i t??ng (OOP)

    Là m?t l?p trình viên m?i làm vi?c v?i Spring Boot, hi?u r? các nguyên t?c c?a L?p trình h??ng ??i t??ng (OOP) là r?t…

    1 条评论
  • Command Query Responsibility Segregation Pattern (CQRS)

    Command Query Responsibility Segregation Pattern (CQRS)

    Command Query Responsibility Segregation (CQRS) là m?u thi?t k? tách bi?t ho?t ??ng ??c và ghi d? li?u trong m?t h?…

    2 条评论
  • ?? Understanding JPA in Java: A Comprehensive Guide to ??? Jakarta Persistence API

    ?? Understanding JPA in Java: A Comprehensive Guide to ??? Jakarta Persistence API

    ?? Introduction to JPA in Java Java Persistence API (JPA) is a standard specification for object-relational mapping…

  • Hibernate: A Comprehensive Guide to Java's Powerful ORM Framework

    Hibernate: A Comprehensive Guide to Java's Powerful ORM Framework

    What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) framework that operates at the persistence layer of…

  • Hibernate Criteria API vs JPQL

    Hibernate Criteria API vs JPQL

    Both Hibernate Criteria API and JPQL are used for querying data in a Hibernate/JPA environment, but they differ in how…

  • N+1 query problem

    N+1 query problem

    1. V?n ?? N+1 query là gì V?n ?? N+1 queries x?y ra khi m?t ORM nh? Hibernate th?c thi m?t truy v?n SQL ?? truy xu?t…

    1 条评论

社区洞察

其他会员也浏览了