只要您不在通话中返回 同一
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;}


