R
R
Rokoss2022-03-28 18:55:59
Java
Rokoss, 2022-03-28 18:55:59

How to make Connection Pool from ThreadLocal?

I'm using ThreadLocal to manage transactions in pure JDBC. Like this

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

public class ConnectionFactory {
    public static ThreadLocal<Connection> connection = new ThreadLocal<>();

    public static Connection createConnection() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:h2:mem:test");
        connection.setAutoCommit(false);
        ConnectionFactory.connection.set(connection);
        return connection;
    }

    public static void quietlyClose() {
        try {
            connection.get().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void quietlyRollback() {
        try {
            connection.get().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

And then in the DAO in the methods we take Connection like this

Connection connection = ConnectionFactory.connection.get();


And in the service we open like this in each method
Connection connection = ConnectionFactory.createConnection();

But how to make a pool under such conditions, I don’t understand at all.

PS Hibernate, Spring is forbidden to use.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question