han*_*nhu 16 java design-patterns jdbc
我写了一个单例类来获取数据库连接.
现在我的问题是:假设有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 .
}
}
Run Code Online (Sandbox Code Playgroud)
请指导我.
Bal*_*usC 24
只要您不在通话中返回相同的 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();
}
}
Run Code Online (Sandbox Code Playgroud)
根据普通的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;
}
Run Code Online (Sandbox Code Playgroud)
下面的代码是一个有效且经过测试的 Java 单例模式。
public class Database {
private static Database dbIsntance;
private static Connection con ;
private static Statement stmt;
private Database() {
// private constructor //
}
public static Database getInstance(){
if(dbIsntance==null){
dbIsntance= new Database();
}
return dbIsntance;
}
public Connection getConnection(){
if(con==null){
try {
String host = "jdbc:derby://localhost:1527/yourdatabasename";
String username = "yourusername";
String password = "yourpassword";
con = DriverManager.getConnection( host, username, password );
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
}
return con;
}
Run Code Online (Sandbox Code Playgroud)
在任何类中获取连接时,只需使用下面的行
Connection con = Database.getInstance().getConnection();
Run Code Online (Sandbox Code Playgroud)
希望它可以帮助:)