DATABASE VALIDATION & JDBC: STATE RECONCILIATION & HIKARICP POOLING

Architect complete end-to-end state verification in REST Assured: Two-phase testing (HTTP wire response vs. physical RDBMS persistence), HikariCP high-performance connection pooling, PreparedStatement parameterized querying, transaction rollbacks for clean test isolation, database tear-down state management, and reconciling wire payloads with relational tables.

πŸ—„οΈ End-to-End Data Verification, Asynchronous State & Database Integrity

Asserting an HTTP status code 200 OK or 201 Created with a valid JSON body is only half of thorough API testing. Often, an API gateway or backend service acknowledges receipt of a payload and echoes back expected attributes, but fails to commit the transaction, silently drops fields during Object-Relational Mapping (ORM), mutates audit timestamps, or leaves dirty state in asynchronous event pipelines. Database Validation via JDBC establishes definitive Two-Phase State Reconciliation. By orchestrating direct database checks in REST Assured automation suitesβ€”leveraging HikariCP connection pooling, parameterized PreparedStatement executions, and AssertJ entity comparisonsβ€”automation engineers confirm that every HTTP POST, PUT, and DELETE cleanly mutates persistent database rows (MySQL, PostgreSQL, Oracle), validates transactional integrity, and executes automated data tear-down routines.

1. Two-Phase API & Database State Reconciliation Architecture
The end-to-end architectural flow of two-phase API testing, contrasting outward HTTP JSON wire validation with inward database state reconciliation executed over pooled JDBC connections.
Two-Phase API & Database Verification Topography
TWO-PHASE API & DATABASE STATE RECONCILIATION ARCHITECTURE:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TEST RUNNER (TestNG + REST Assured Test Suite)                                                β”‚
β”‚ StudentRegistrationRequest payload = StudentDataFactory.createValidStudent();                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β–Ό (PHASE 1: HTTP WIRE TRANSMISSION)                    β–Ό (PHASE 2: DIRECT JDBC RECONCILIATION)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ HTTP API GATEWAY / MICROSERVICE PIPELINE     β”‚      β”‚ HIKARICP CONNECTION POOL (Pooled DataSource) β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€      β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1. POST /v1/students                         β”‚      β”‚ 1. Rent Connection: ConnectionPool.getConn() β”‚
β”‚ 2. Backend ORM saves to Database             β”‚      β”‚ 2. SELECT * FROM students WHERE id = ?       β”‚
β”‚ 3. Server returns HTTP 201 Created           β”‚      β”‚ 3. Extract ResultSet to StudentEntity model  β”‚
β”‚ 4. REST Assured asserts status & JSON body   β”‚      β”‚ 4. Reconcile DB fields against Wire payload  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ CROSS-TIER ASSERTION RECONCILIATION (AssertJ)                                                 β”‚
β”‚  β”œβ”€β”€ assertThat(dbEntity.getFullName()).isEqualTo(apiResponse.getFullName());                 β”‚
β”‚  β”œβ”€β”€ assertThat(dbEntity.getEnrolledCredits()).isEqualTo(payload.getEnrolledCredits());       β”‚
β”‚  β”œβ”€β”€ assertThat(dbEntity.getCreatedTimestamp()).isCloseTo(Instant.now(), within(5, SECONDS)); β”‚
β”‚  └── assertThat(dbEntity.getTenantRegion()).isEqualTo("MH-PUNE-WEST");                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TEARDOWN / DATA PURGE PHASE (@AfterMethod)                                                    β”‚
β”‚ DELETE FROM students WHERE student_id = ? (Ensures 100% zero-footprint test isolation)        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Never rely on DriverManager.getConnection() in automated suites. Repeated connection handshakes under parallel test runs exhaust database socket limits. Always use an enterprise connection pool like HikariCP to reuse warm connections across concurrent TestNG threads.
Real-Time Example 1: High-Performance Database Manager with HikariCP (DatabaseManager.java)
Building an enterprise connection pool manager using HikariCP. Manages database credentials, configures connection timeouts, and provides thread-safe access to SQL execution utilities.
Java (DatabaseManager.java Pooled Connection Engine)
package com.nikita.restassured.database;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class DatabaseManager {

    private static final HikariDataSource dataSource;

    static {
        // Read database configuration from system flags or properties
        String jdbcUrl = System.getProperty("db.url", "jdbc:mysql://localhost:3306/enterprise_masterclass?useSSL=false&serverTimezone=UTC");
        String username = System.getProperty("db.user", "sdet_tester");
        String password = System.getProperty("db.password", "TestPass#2026");

        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(jdbcUrl);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");

        // Connection pool sizing and tuning
        config.setMaximumPoolSize(15);         // Max concurrent connections in pool
        config.setMinimumIdle(5);              // Minimum warm idle connections
        config.setConnectionTimeout(10000);    // 10s timeout to rent connection
        config.setIdleTimeout(600000);         // 10 minutes idle timeout
        config.setMaxLifetime(1800000);        // 30 minutes max connection lifetime
        config.setPoolName("RestAssuredHikariPool");

        dataSource = new HikariDataSource(config);
        System.out.println("[*] HikariCP Connection Pool initialized successfully.");
    }

    /**
     * Rents an active connection from the pool
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * Graceful teardown of pool during suite shutdown
     */
    public static void shutdown() {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
            System.out.println("[*] HikariCP Connection Pool closed.");
        }
    }
}
HikariCP Pool Telemetry: [*] HikariCP Connection Pool initialized successfully. Pool Name: RestAssuredHikariPool | MaxPoolSize: 15 | MinIdle: 5 Warm connections pre-allocated; provides sub-millisecond connection checkout for parallel test threads.
Real-Time Example 2: Reusable Database Query Helper (StudentDao.java)
Designing a Data Access Object (DAO) for test assertions. Encapsulates PreparedStatement queries, extracts records into typed entity objects, checks row existence, and executes parameterized test cleanup routines.
Java (StudentDao.java Parameterized Query & Persistence Helper)
package com.nikita.restassured.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Optional;

public class StudentDao {

    public static class StudentDbRecord {
        public String studentId;
        public String fullName;
        public String email;
        public String academicTrack;
        public int enrolledCredits;
        public String status;
        public Timestamp createdAt;
    }

    /**
     * Queries a student record by unique primary key
     */
    public Optional<StudentDbRecord> getStudentById(String studentId) {
        String sql = "SELECT student_id, full_name, email, academic_track, enrolled_credits, status, created_at " +
                     "FROM students WHERE student_id = ?";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, studentId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    StudentDbRecord record = new StudentDbRecord();
                    record.studentId = rs.getString("student_id");
                    record.fullName = rs.getString("full_name");
                    record.email = rs.getString("email");
                    record.academicTrack = rs.getString("academic_track");
                    record.enrolledCredits = rs.getInt("enrolled_credits");
                    record.status = rs.getString("status");
                    record.createdAt = rs.getTimestamp("created_at");
                    return Optional.of(record);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("Database query failed for studentId: " + studentId, e);
        }
        return Optional.empty();
    }

    /**
     * Purges a student record created during testing (Teardown routine)
     */
    public boolean deleteStudentById(String studentId) {
        String sql = "DELETE FROM students WHERE student_id = ?";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, studentId);
            int rowsDeleted = stmt.executeUpdate();
            return rowsDeleted > 0;
        } catch (SQLException e) {
            throw new RuntimeException("Database cleanup failed for studentId: " + studentId, e);
        }
    }
}
DAO Layer Standard: - All queries use PreparedStatement placeholders (?) to prevent SQL injection and syntax errors. - Uses try-with-resources on Connection, PreparedStatement, and ResultSet to ensure clean resource return. - Returns Optional<T> to cleanly handle missing database records without NullPointerExceptions.
Real-Time Example 3: Two-Phase Verification: POST API Request & Database State Reconciliation
Executing a complete two-phase verification test. Dispatches an HTTP POST in REST Assured, verifies the 201 Created wire response, then queries the physical database to reconcile column values and timestamps.
Java (TwoPhaseRegistrationVerificationTest.java)
package com.nikita.restassured.database;

import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import com.nikita.restassured.models.response.StudentProfileResponse;
import org.assertj.core.api.Assertions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;

public class TwoPhaseRegistrationVerificationTest {

    private StudentServiceClient studentClient;
    private StudentDao studentDao;
    private String registeredStudentId;

    @BeforeClass
    public void setup() {
        studentClient = new StudentServiceClient();
        studentDao = new StudentDao();
    }

    @Test(description = "Two-Phase Verification: Verify HTTP 201 wire response matches physical database row")
    public void testStudentRegistrationWithDatabaseReconciliation() {
        // Arrange: Generate dynamic valid candidate payload
        StudentRegistrationRequest payload = StudentDataFactory.createValidStudent();
        registeredStudentId = payload.getStudentId();

        // -------------------------------------------------------------
        // PHASE 1: HTTP WIRE TRANSMISSION & RESPONSE VALIDATION
        // -------------------------------------------------------------
        StudentProfileResponse wireResponse = studentClient.registerStudent(payload);

        Assertions.assertThat(wireResponse.getId())
                .as("Wire response ID must match request ID")
                .isEqualTo(payload.getStudentId());

        Assertions.assertThat(wireResponse.getStatus())
                .as("Wire response status check")
                .isEqualTo("ACTIVE");

        System.out.println("[Phase 1] HTTP Wire response validated: 201 Created for ID: " + registeredStudentId);

        // -------------------------------------------------------------
        // PHASE 2: DIRECT DATABASE QUERY & STATE RECONCILIATION
        // -------------------------------------------------------------
        Optional<StudentDao.StudentDbRecord> dbRecordOpt = studentDao.getStudentById(registeredStudentId);

        Assertions.assertThat(dbRecordOpt)
                .as("Physical database row must exist in 'students' table")
                .isPresent();

        StudentDao.StudentDbRecord dbRecord = dbRecordOpt.get();

        // Reconcile physical DB columns against request payload & wire response:
        Assertions.assertThat(dbRecord.fullName)
                .as("DB column 'full_name' must match wire payload")
                .isEqualTo(payload.getFullName());

        Assertions.assertThat(dbRecord.email)
                .as("DB column 'email' must match wire payload")
                .isEqualTo(payload.getEmail());

        Assertions.assertThat(dbRecord.enrolledCredits)
                .as("DB column 'enrolled_credits' must match wire payload")
                .isEqualTo(payload.getEnrolledCredits());

        Assertions.assertThat(dbRecord.status)
                .as("DB column 'status' must be ACTIVE")
                .isEqualTo("ACTIVE");

        // Verify audit timestamp was populated within the last 10 seconds:
        Assertions.assertThat(dbRecord.createdAt.toInstant())
                .as("DB column 'created_at' timestamp must reflect recent insertion")
                .isCloseTo(Instant.now(), Assertions.within(10, ChronoUnit.SECONDS));

        System.out.println("[Phase 2] Database row reconciled: All DB columns match wire payload accurately.");
    }

    @AfterMethod(alwaysRun = true)
    public void teardownTestData() {
        if (registeredStudentId != null) {
            boolean deleted = studentDao.deleteStudentById(registeredStudentId);
            System.out.println("[Teardown] Purged student record from database: " + registeredStudentId + " (Success: " + deleted + ")");
        }
    }
}
Two-Phase Execution Telemetry: POST /v1/students -> HTTP 201 Created [122ms] [Phase 1] HTTP Wire response validated: 201 Created for ID: STU-58921 SQL Query: SELECT * FROM students WHERE student_id = 'STU-58921' [3ms via HikariCP] [Phase 2] Database row reconciled: All DB columns match wire payload accurately. β€’ full_name: "Candidate_a4c9e1" (MATCH) β€’ enrolled_credits: 16 (MATCH) β€’ status: "ACTIVE" (MATCH) β€’ created_at: 2026-11-03 10:45:12.482 UTC (Close to now within 10s) [Teardown] Purged student record from database: STU-58921 (Success: true) PASSED: testStudentRegistrationWithDatabaseReconciliation
Real-Time Example 4: Testing DELETE API & Confirming Row Deletion in Database
Verifying destructive operations. Issues an HTTP DELETE to remove a student entity, checks the 204 No Content status code, and queries the database via JDBC to confirm that the physical row was purged.
Java (DeleteVerificationWithDatabaseTest.java)
package com.nikita.restassured.database;

import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import io.restassured.response.Response;
import org.assertj.core.api.Assertions;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Optional;

public class DeleteVerificationWithDatabaseTest {

    private StudentServiceClient studentClient;
    private StudentDao studentDao;

    @BeforeClass
    public void setup() {
        studentClient = new StudentServiceClient();
        studentDao = new StudentDao();
    }

    @Test(description = "Verify HTTP DELETE returns 204 and physically purges row from database")
    public void testDeleteStudentDatabaseVerification() {
        // Step 1: Pre-condition - Register a student to delete
        StudentRegistrationRequest student = StudentDataFactory.createValidStudent();
        studentClient.registerStudent(student);
        String targetId = student.getStudentId();

        // Confirm row is present in DB prior to deletion
        Assertions.assertThat(studentDao.getStudentById(targetId)).isPresent();
        System.out.println("[*] Pre-condition confirmed: Student row exists in DB: " + targetId);

        // Step 2: Act - Execute HTTP DELETE via Service Client
        Response deleteResponse = studentClient.deleteStudent(targetId);

        // Assert HTTP status code is 204 No Content
        Assertions.assertThat(deleteResponse.getStatusCode())
                .as("DELETE endpoint must return HTTP 204 No Content")
                .isEqualTo(204);

        System.out.println("[*] DELETE /v1/students/" + targetId + " returned HTTP 204 No Content.");

        // Step 3: Assert - Verify physical database state
        Optional<StudentDao.StudentDbRecord> recordAfterDelete = studentDao.getStudentById(targetId);

        Assertions.assertThat(recordAfterDelete)
                .as("Student row must be completely removed from database after HTTP DELETE")
                .isEmpty();

        System.out.println("[βœ”] Database verified: Record " + targetId + " successfully purged from database table.");
    }
}
DELETE Verification Output: POST /v1/students -> HTTP 201 Created [98ms] [*] Pre-condition confirmed: Student row exists in DB: STU-88219 DELETE /v1/students/STU-88219 -> HTTP 204 No Content [44ms] [*] DELETE /v1/students/STU-88219 returned HTTP 204 No Content. SELECT * FROM students WHERE student_id = 'STU-88219' -> 0 rows returned [βœ”] Database verified: Record STU-88219 successfully purged from database table. PASSED: testDeleteStudentDatabaseVerification
Real-Time Example 5: Asynchronous Event Persistence Validation (Polling with Awaitility)
Handling eventual consistency in event-driven systems. Uses Awaitility to poll the database asynchronously after an HTTP request, verifying that background workers (Kafka consumers, RabbitMQ queues) write the expected row within an SLA window.
Java (Asynchronous Event Persistence Validation with Awaitility)
package com.nikita.restassured.database;

import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import org.assertj.core.api.Assertions;
import org.awaitility.Awaitility;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

public class AsyncDatabaseValidationTest {

    private final StudentServiceClient studentClient = new StudentServiceClient();
    private final StudentDao studentDao = new StudentDao();
    private String asyncStudentId;

    @Test(description = "Verify asynchronous event-driven database persistence using Awaitility polling")
    public void testAsyncEventPersistence() {
        StudentRegistrationRequest payload = StudentDataFactory.createValidStudent();
        asyncStudentId = payload.getStudentId();

        // Dispatch async registration request (HTTP 202 Accepted)
        studentClient.registerStudentRaw(payload)
                .then()
                .statusCode(201);

        System.out.println("[*] Dispatched registration. Polling database for asynchronous consumer write...");

        AtomicReference<StudentDao.StudentDbRecord> recordRef = new AtomicReference<>();

        // Poll database every 500ms for up to 5 seconds until the background worker writes the row
        Awaitility.await()
                .atMost(Duration.ofSeconds(5))
                .pollInterval(Duration.ofMillis(500))
                .alias("Wait for Kafka consumer to persist student record to database")
                .untilAsserted(() -> {
                    Optional<StudentDao.StudentDbRecord> record = studentDao.getStudentById(asyncStudentId);
                    Assertions.assertThat(record).isPresent();
                    recordRef.set(record.get());
                });

        StudentDao.StudentDbRecord persistedRecord = recordRef.get();
        Assertions.assertThat(persistedRecord.status).isEqualTo("ACTIVE");
        Assertions.assertThat(persistedRecord.fullName).isEqualTo(payload.getFullName());

        System.out.println("[βœ”] Asynchronous persistence confirmed: Record found in database within SLA window.");
    }

    @AfterMethod(alwaysRun = true)
    public void cleanUp() {
        if (asyncStudentId != null) {
            studentDao.deleteStudentById(asyncStudentId);
        }
    }
}
Async Polling Telemetry: POST /v1/students -> HTTP 201 Created [86ms] [*] Dispatched registration. Polling database for asynchronous consumer write... Poll 1 (500ms): Record not found... Poll 2 (1000ms): Record not found... Poll 3 (1500ms): Record located! [βœ”] Asynchronous persistence confirmed: Record found in database within SLA window. Avoids fragile Thread.sleep() calls by polling dynamically with Awaitility.
Real-Time Example 6: Multi-Tenant Data Isolation Checks via Database Queries
Validating multi-tenant data boundaries. Creates entities under one tenant context and queries the database directly to confirm that tenant identifiers (e.g. tenant_id) are saved correctly and rows remain hidden from other tenants.
Java (MultiTenantDatabaseIsolationTest.java)
package com.nikita.restassured.database;

import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import org.assertj.core.api.Assertions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MultiTenantDatabaseIsolationTest {

    private final StudentServiceClient studentClient = new StudentServiceClient();
    private final StudentDao studentDao = new StudentDao();
    private String testStudentId;

    @Test(description = "Verify student record is persisted with strict tenant partitioning in database")
    public void testTenantPartitioningInDatabase() throws SQLException {
        StudentRegistrationRequest student = StudentDataFactory.createValidStudent();
        testStudentId = student.getStudentId();

        // Register student under Pune tenant
        studentClient.registerStudent(student);

        // Direct SQL checking tenant association
        String sql = "SELECT tenant_id FROM students WHERE student_id = ?";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, testStudentId);

            try (ResultSet rs = stmt.executeQuery()) {
                Assertions.assertThat(rs.next())
                        .as("Record must exist in database")
                        .isTrue();

                String assignedTenant = rs.getString("tenant_id");
                System.out.println("[*] Queried tenant_id from database: " + assignedTenant);

                Assertions.assertThat(assignedTenant)
                        .as("Tenant ID must be partitioned to Pune region")
                        .isEqualTo("MH-PUNE-WEST");
            }
        }

        System.out.println("[βœ”] Multi-tenant isolation verified: Row is correctly tagged with tenant identifier.");
    }

    @AfterMethod(alwaysRun = true)
    public void cleanUp() {
        if (testStudentId != null) {
            studentDao.deleteStudentById(testStudentId);
        }
    }
}
Tenant Partitioning Output: POST /v1/students -> HTTP 201 Created [114ms] [*] Queried tenant_id from database: MH-PUNE-WEST Assertions: tenant_id == "MH-PUNE-WEST" (MATCH) [βœ”] Multi-tenant isolation verified: Row is correctly tagged with tenant identifier. PASSED: testTenantPartitioningInDatabase
Real-Time Example 7: Database Seeding & Fixture Injection for Pre-Conditions
Seeding database pre-conditions directly via SQL. Demonstrates inserting prerequisite reference records (e.g., student accounts, prerequisite courses) into the database to set up test scenarios without calling setup APIs.
Java (DatabaseSeedingHelper.java Direct Pre-Condition Injection)
package com.nikita.restassured.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;

public class DatabaseSeedingHelper {

    /**
     * Directly inserts a prerequisite student record into the database for testing GET/PUT operations
     */
    public static void seedStudent(String studentId, String fullName, String email, String track, int credits) {
        String sql = "INSERT INTO students (student_id, full_name, email, academic_track, enrolled_credits, status, tenant_id, created_at) " +
                     "VALUES (?, ?, ?, ?, ?, 'ACTIVE', 'MH-PUNE-WEST', ?) " +
                     "ON DUPLICATE KEY UPDATE full_name = VALUES(full_name), status = 'ACTIVE'";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, studentId);
            stmt.setString(2, fullName);
            stmt.setString(3, email);
            stmt.setString(4, track);
            stmt.setInt(5, credits);
            stmt.setTimestamp(6, Timestamp.from(Instant.now()));

            int rows = stmt.executeUpdate();
            System.out.printf("[DB SEED] Seeded student record '%s' directly into DB (Rows affected: %d)%n", 
                    studentId, rows);

        } catch (SQLException e) {
            throw new RuntimeException("Failed to seed student record: " + studentId, e);
        }
    }
}
Database Seeding Telemetry: [DB SEED] Seeded student record 'STU-PRE-EXISTING-101' directly into DB (Rows affected: 1) Tests query pre-seeded records via REST Assured immediately without relying on separate POST endpoints for test setup.
Real-Time Example 8: Debugging JDBC Timeouts & Connection Leak Triage
Troubleshooting common database testing issues: diagnosing ConnectionPoolTimeoutException, preventing unclosed statements, tuning query timeouts, and resolving transaction isolation deadlocks in parallel test suites.
Java (Triage: Diagnosing Connection Leaks & Statement Timeouts)
package com.nikita.restassured.database;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DatabaseTriageTest {

    // ==========================================================================
    // PITFALL 1: CONNECTION POOL EXHAUSTION DUE TO UNCLOSED STATEMENTS / CONNS
    // SYMPTOM: com.zaxxer.hikari.pool.HikariPool$PoolBag: Connection timeout
    //
    // CAUSE: Code opens a Connection without closing it, holding it open indefinitely.
    // Under parallel TestNG runs, all 15 connections are locked, starving worker threads!
    //
    // FIX: Always enclose Connection, PreparedStatement, and ResultSet inside
    // a try-with-resources statement!
    // ==========================================================================

    @Test(description = "Verify safe query execution with statement timeout and zero connection leakage")
    public void testSafeQueryWithTimeout() {
        String sql = "SELECT 1";

        // All 3 JDBC objects declared inside try-with-resources guarantees automatic closure:
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // Enforce explicit statement timeout (e.g. 3 seconds) to prevent hanging tests:
            stmt.setQueryTimeout(3);

            try (ResultSet rs = stmt.executeQuery()) {
                Assert.assertTrue(rs.next());
                Assert.assertEquals(rs.getInt(1), 1);
            }

            System.out.println("[βœ”] Executed query safely with auto-closure and explicit 3s statement timeout.");

        } catch (SQLException e) {
            Assert.fail("Database query execution failed: " + e.getMessage());
        }
    }
}
Triage Diagnostic Breakdown: - HikariPool Connection Timeout: Resolved by wrapping all Connection checkouts in try-with-resources. - Hanging Queries: Resolved by setting stmt.setQueryTimeout(3), failing fast if the database experiences a lock or deadlock. - Thread Safety: Pooled connections are checked out and returned per query, ensuring zero thread contention.
Real-Time Example 9: Database Validation Specification Reference Matrix
A comprehensive reference summary pairing database operations, JDBC constructs, validation strategies, and operational best practices for REST Assured test automation architects.
Database Validation Specification Reference Matrix
DATABASE VALIDATION SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ VALIDATION CONSTRUCT    β”‚ JDBC / UTILITY MECHANISM     β”‚ LIFECYCLE TIER   β”‚ PRIMARY OPERATIONAL PURPOSE   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ HikariCP Pool           β”‚ HikariDataSource             β”‚ Global Singleton β”‚ High-speed connection reuse   β”‚
β”‚ Parameterized Query     β”‚ PreparedStatement (?)        β”‚ DAO Layer        β”‚ Prevents SQL injection bugs   β”‚
β”‚ Try-With-Resources      β”‚ try (Connection, Stmt, RS)   β”‚ Execution Block  β”‚ Guarantees zero socket leaks  β”‚
β”‚ Statement Timeout       β”‚ stmt.setQueryTimeout(3)      β”‚ Query Level      β”‚ Fails fast on locked rows     β”‚
β”‚ Two-Phase Validation    β”‚ REST Assured + JDBC DAO      β”‚ Test Method      β”‚ Wire response vs. DB state    β”‚
β”‚ Eventual Consistency    β”‚ Awaitility.await().until(..) β”‚ Async Testing    β”‚ Polls DB for async queue writeβ”‚
β”‚ Data Seeding            β”‚ DatabaseSeedingHelper        β”‚ Pre-Condition    β”‚ Sets up prerequisites via SQL β”‚
β”‚ Automated Teardown      β”‚ DAO.deleteById(studentId)    β”‚ @AfterMethod     β”‚ Zero-footprint test isolation β”‚
β”‚ Tenant Isolation Audit  β”‚ SELECT tenant_id WHERE id=?  β”‚ Security Audit   β”‚ Verifies multi-tenant bounds  β”‚
β”‚ AssertJ Reconciliation  β”‚ assertThat(db).isEqualTo(reqβ”‚ Assertion Phase  β”‚ Strong entity reconciliation   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 DATABASE VALIDATION BEST PRACTICES:                                                                 β”‚
β”‚ 1. Always use connection pooling: Use HikariCP to prevent socket exhaustion during parallel runs.         β”‚
β”‚ 2. Enclose all JDBC calls in try-with-resources: Prevent connection leaks in long-running CI runners.     β”‚
β”‚ 3. Always clean up test data in @AfterMethod: Ensure test entities are purged to avoid dirty state.       β”‚
β”‚ 4. Use Awaitility for asynchronous events: Poll the database with an SLA window for queue consumers.      β”‚
β”‚ 5. Parameterize SQL with PreparedStatement: Avoid manual string concatenation and SQL injection flaws.    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Two-phase verification elevates API automation from superficial HTTP checking to comprehensive state reconciliation. By pairing REST Assured wire assertions with HikariCP-backed JDBC validations, verifying row deletions, polling asynchronous event persistence via Awaitility, and cleaning up test state in @AfterMethod teardowns, you build enterprise-ready test frameworks that guarantee data integrity across your entire architecture.