All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.babyfish.jimmer.sql.runtime.ConnectionManager Maven / Gradle / Ivy

There is a newer version: 0.8.180
Show newest version
package org.babyfish.jimmer.sql.runtime;

import org.jetbrains.annotations.Nullable;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Objects;
import java.util.function.Function;

@FunctionalInterface
public interface ConnectionManager {

    ConnectionManager EXTERNAL_ONLY = new ConnectionManager() {
        @Override
        public  R execute(@Nullable Connection con, Function block) {
            Objects.requireNonNull(con, "External connection cannot be null");
            return block.apply(con);
        }
    };

    static ConnectionManager singleConnectionManager(Connection connection) {
        return new ConnectionManager() {
            @Override
            public  R execute(@Nullable Connection con, Function block) {
                return block.apply(con == null ? connection : con);
            }
        };
    }

    static ConnectionManager simpleConnectionManager(DataSource dataSource) {
        return new ConnectionManager() {
            @Override
            public  R execute(@Nullable Connection con, Function block) {
                try {
                    return block.apply(con);
                } catch (RuntimeException | Error ex) {
                    throw ex;
                } catch (Throwable ex) {
                    throw new ExecutionException(ex.getMessage(), ex);
                }
            }

            @Override
            public  R execute(Function block) {
                try (Connection con = dataSource.getConnection()) {
                    return block.apply(con);
                } catch (RuntimeException | Error ex) {
                    throw ex;
                } catch (Throwable ex) {
                    throw new ExecutionException(ex.getMessage(), ex);
                }
            }
        };
    }

     R execute(@Nullable Connection con, Function block);

    default  R execute(Function block) {
        return execute(null, block);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy