Ho il codice seguente:Come riutilizzare la stessa connessione con un JdbcTemplate di Spring?
@Test
public void springTest() throws SQLException{
//Connect to the DB.
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:/data/h2/testa");
dataSource.setUsername("");
dataSource.setPassword("");
JdbcTemplate jt=new JdbcTemplate(dataSource);
jt.execute("SELECT 1");
jt.execute("SELECT 1");
}
mi aspetto i due execute() linee di riutilizzare la stessa connessione. Tuttavia, l'output del registro dice:
2011-02-10 12:24:17 DriverManagerDataSource [INFO] Loaded JDBC driver: org.h2.Driver 2011-02-10 12:24:17 JdbcTemplate [DEBUG] Executing SQL statement [SELECT 1] 2011-02-10 12:24:17 DataSourceUtils [DEBUG] Fetching JDBC Connection from DataSource 2011-02-10 12:24:17 DriverManagerDataSource [DEBUG] Creating new JDBC DriverManager Connection to [jdbc:h2:/data/h2/testa] 2011-02-10 12:24:17 DataSourceUtils [DEBUG] Returning JDBC Connection to DataSource 2011-02-10 12:24:17 JdbcTemplate [DEBUG] Executing SQL statement [SELECT 1] 2011-02-10 12:24:17 DataSourceUtils [DEBUG] Fetching JDBC Connection from DataSource 2011-02-10 12:24:17 DriverManagerDataSource [DEBUG] Creating new JDBC DriverManager Connection to [jdbc:h2:/data/h2/testa] 2011-02-10 12:24:17 DataSourceUtils [DEBUG] Returning JDBC Connection to DataSource
L'esempio sopra corre abbastanza veloce, ma ho un pezzo più grande di codice che fa fondamentalmente la stessa cosa e si blocca per un lungo periodo di tempo sul Creating new JDBC DriverManager Connection
. Non ricevo mai un errore ma il codice si esegue molto lentamente. Posso in qualche modo rifattare il codice sopra per usare la stessa connessione?
Grazie
Questo è un cambiamento facile e sembrava aver funzionato. È thread-safe? – User1
È thread-safe, perché questo è ciò che è un pool di connessioni. :) L'ho usato anche nei miei casi di test, concedendo che leghi 'dataSource' invece di crearlo a livello di codice. – limc
Wow, il mio grande codice è diventato 100 volte più veloce! – User1