說明,使用Spring4, 採用 Java Configuration.
java
<一> 配置數據源 之五種方式sql
1. 使用 JNDI 的數據源(jndi data source)數據庫
代碼以下:tcp
@Bean public JndiObjectFactoryBean dataSource() { JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean(); jndiObjectFB.setJndiName("jdbc/XXXDS"); jndiObjectFB.setResourceRef(true); jndiObjectFB.setProxyInterface(javax.sql.DataSource.class); return jndiObjectFB; }
說明,這是利用JndiObjectFactoryBean 從JNDI 中查找DataSource性能
2.使用數據源池(data source pool)
測試
@Bean public BasicDataSource dataSource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("org.h2.Driver"); ds.setUrl("jdbc:h2:tcp://localhost/~/XXX"); ds.setUsername("sa"); ds.setPassword(""); ds.setInitialSize(5); ds.setMaxActive(10); return ds; }
driverclassname、url、username以及password 是BasicDataSource 配置的基本元素。
ui
其它的還有:initialSize、maxActive、maxIdle、maxOpenPreparedStatements、maxWait、minEvictableIdleTimeMillis、minIdle、poolPreparedStatements。this
3. 使用基於JDBC 驅動的數據源(jdbc driver-base data source)url
有三個JDBC data source class:DriverManagerDataSource、SimpleDriverDataSource和SingleConnectionDataSourcespa
舉個例子,配置DriverManagerDataSource:
@Bean public DataSource dataSource() { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("org.h2.Driver"); ds.setUrl("jdbc:h2:tcp://localhost/~/XXX"); ds.setUsername("sa"); ds.setPassword(""); return ds; }
說明,因爲這個datasource ,在每次請求時,都會建立一個新的鏈接,從而犧牲了性能。因此,在生產環境中,儘可能要使用數據源池的方式。
4.使用嵌入的數據源(embedded data source)
至關於內存數據庫,在開發和測試時,比較有用。
舉例:
@Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("classpath:schema.sql") .addScript("classpath:test-data.sql") .build(); }
說明,H2 要加在classpath中。
5. 使用 profiles 來選擇數據源,
舉例:
@Configuration public class DataSourceConfiguration { @Profile("development") @Bean public DataSource embeddedDataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("classpath:schema.sql") .addScript("classpath:test-data.sql") .build(); } @Profile("qa") @Bean public DataSource Data() { // ...... }
說明:在啓動的時候,指明哪一個profile 是 active 的。
<二> 在Spring 中使用JDBC
1.Spring 提供了三種JDBC 的模板
JdbcTemplate
NameParameterJdbcTemplate
SimpleJdbcTemplate
2. JDBC 模板的操做
經過@Bean,將DataSource 賦給JDBCTemplate,就能夠使用這些模板。
舉例:
@Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); }
經過將JDBC 的Template 注入進Repository 便可使用。即在ComponentScan 的時候,建立了該模板。舉例:
@Repository public class JdbcSpitterRepository implements SpitterRepository { private JdbcOperations jdbcOperations; @Inject public JdbcSpitterRepository(JdbcOperations jdbcOperations) { this.jdbcOperations = jdbcOperations; } ... }
剩下的就是使用該模板進行CRUD 操做。