如果我使用单例类进行数据库连接,那么一个用户可以为所有人关闭该连接吗?


问题内容

我写了一个单例类来获取数据库连接。

现在我的问题是:假设有100个用户正在访问该应用程序。如果一个用户关闭连接,对于其他99个用户,连接是否关闭?

这是我的示例程序,它使用单例类获取数据库连接:

public class GetConnection {

    private GetConnection() { }

    public Connection getConnection() {
        Context ctx = new InitialContext();
        DataSource ds = ctx.lookup("jndifordbconc");
        Connection con = ds.getConnection();
        return con;
    }

    public static  GetConnection   getInstancetoGetConnection () {
        // which gives GetConnection class instance to call getConnection() on this .
    }
}

请指导我。


问题答案:

只要您不在通话中返回 同一
Connection实例,就不必getConnection()担心。然后,每个调用者都将获得自己的实例。到目前为止,您将在每个getConnection()调用上创建一个全新的连接,因此不会返回任何静态或实例变量。这样很安全。

但是,这种方法笨拙。不必是单身人士。辅助/实用程序类也很好。或者,如果您想要更多的抽象,可以使用抽象工厂返回的连接管理器。我只更改它即可在类初始化期间获取一次数据源,而不是每次都在中获取数据源getConnection()。无论如何,都是同一实例。保持便宜。这是一个基本的启动示例:

public class Database {

    private static DataSource dataSource;

    static {
        try {
            dataSource = new InitialContext().lookup("jndifordbconc");
        }
        catch (NamingException e) { 
            throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);
        }
    }

    public static Connection getConnection() {
        return dataSource.getConnection();
    }

}

根据常规的JDBC习惯用法如下。

public List<Entity> list() throws SQLException {
    List<Entity> entities = new ArrayList<Entity>();

    try (
        Connection connection = Database.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
        ResultSet resultSet = statement.executeQuery();
    ) {
        while (resultSet.next()) {
            Entity entity = new Entity();
            entity.setId(resultSet.getLong("id"));
            entity.setFoo(resultSet.getString("foo"));
            entity.setBar(resultSet.getString("bar"));
            entities.add(entity);
        }
    }

    return entities;
}