0
我想了解连接pool.For例子的概念连接,我在META-INF下面的XML文件与我的数据库设置静态类来获得从连接池
<Resource name="jdbc/appname"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
minIdle="10"
username="postgres"
password="123"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:5432/Lab4"/>
要使用我使用连接池在folliwng类
public class DataBaseConnection {
private static DataSource dataSource;
static {
try {
InitialContext initContext = new InitialContext();
dataSource = (DataSource) initContext.lookup("java:comp/env/jdbc/appname");
} catch (NamingException ex) {
throw new RuntimeException(ex);
}
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
这是使用
public class UserQueries{
public User selectUserByLoginAndPassword(final String login, final String password) {
try(Connection connection=DataBaseConnection.getConnection())
try (PreparedStatement st = connection.prepareStatement(SELECT_QUERY)) {
st.setString(1, login);
st.setString(2, password);
ResultSet result = st.executeQuery();
while (result.next()) {
final User user = User.newBuilder()
.setId(result.getInt("id"))
.setAge(result.getInt("age"))
.setName(result.getString("name"))
.setPassword(result.getString("password"))
.setLogin(login)
.build();
return user;
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new NullPointerException("Nu such user in db");
}
}
的问题是,如果我莫迪FY的DatabaseConnection以下列方式,
public class DataBaseConnection {
private DataSource dataSource;
public DataBaseConnection()
try {
InitialContext initContext = new InitialContext();
dataSource = (DataSource) initContext.lookup("java:comp/env/jdbc/appname");
} catch (NamingException ex) {
throw new RuntimeException(ex);
}
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
,我将建立在每个使用DB conections类新的DatabaseConnection对象,这是否意味着每个类(例如UserQueries)将创建中隔离池连接如使用?
例
public class UserQueries{
private DataBaseConnection dbCon = new DataBaseConnection();
public User selectUserByLoginAndPassword(final String login, final String password) {
try(Connection connection = dbCon.getConnection())
try (PreparedStatement st = connection.prepareStatement(SELECT_QUERY)) {
st.setString(1, login);
st.setString(2, password);
ResultSet result = st.executeQuery();
while (result.next()) {
final User user = User.newBuilder()
.setId(result.getInt("id"))
.setAge(result.getInt("age"))
.setName(result.getString("name"))
.setPassword(result.getString("password"))
.setLogin(login)
.build();
return user;
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new NullPointerException("Nu such user in db");
}
}
每一个实例被创建这是否意味着使用我的applcation将使用只有一个连接池静态数据源保证? –
更好地说:使用一个'DataSource'实例是最好的方法。 “...我的applcation将使用唯一的连接池?” _--是的 – wiseOne