说明,使用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 操做。