-
在声明模板和Repository之前, 我们需要先在Spring中配置一个数据源用于数据库连接
-
Spring提供了多种配置数据源bean的方式
(1) JDBC驱动程序定义的数据源
(2) JNDI查找的数据源
(3) 连接池的数据源
(4) 嵌入式数据源
-
使用JNDI数据源 P294
-
使用连接池数据源 P295
-
基于JDBC驱动的数据源
(1) 种类
1° DriverManagerDateSource: 每次有连接请求时都返回一个新建的连接
2° SimpleDriverDataSource: 和DriverManagerDateSource的工作方式类似, 但是直接使用JDBC驱动来解决特定环境下的类加载问题, 例如OSGI容器
3° SingleConnectionDataSource: 只有一个Connection的数据库连接池
(2) 示例
@Configuration public class JdbcConfig { @Bean public DataSource jdbcDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/spitt"); dataSource.setUsername("haha"); dataSource.setPassword("123456"); return dataSource; } ... } -
使用嵌入式的数据源
(1) 嵌入式数据库作为应用的一部分运行, 每次重启应用时都会__重新填充__测试数据
(2) 示例: 使用嵌入式的H2数据库
@Configuration public class JdbcConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScripts("classpath:spittr/db/jdbc/schema.sql", "classpath:spittr/db/jdbc/test-data.sql") .build(); } ... }EmbeddedDatabaseBuilder使用了生成器模式, 它包含了各种addXXX,setXXX方式用于添加参数, 最后调用build会返回一个EmbeddedDatabase对象, 而EmbeddedDatabase继承于DataSource;
schema.sql是创建数据库的脚本, test-data是向数据库中添加测试数据的脚本
schema.sql
drop table if exists spittle; drop table if exists spitter; create table spitter ( id identity, username varchar(25) not null, password varchar(25) not null, fullName varchar(100) not null, email varchar(50) not null, updateByEmail boolean not null ); create table spittle ( id integer identity primary key, spitter integer not null, message varchar(2000) not null, postedTime datetime not null, foreign key (spitter) references spitter(id) );test-data.sql
insert into Spitter (username, password, fullname, email, updateByEmail) values ('habuma', 'password', 'Craig Walls', 'craig@habuma.com', false); insert into Spitter (username, password, fullname, email, updateByEmail) values ('mwalls', 'password', 'Michael Walls', 'mwalls@habuma.com', true); ... insert into Spittle (spitter, message, postedTime) values (1, 'This is a test spittle message', '2012-06-09 22:00:00Z'); insert into Spittle (spitter, message, postedTime) values (1, 'This is another test spittle message', '2012-06-09 22:10:00Z'); ... -
使用__@profile__可以根据环境在运行时选择哪种数据库
chapter10_通过Spring和JDBC征服数据库_2_配置数据源
最新推荐文章于 2023-03-30 21:38:40 发布
本文详细介绍了Spring框架中数据源的配置方法,包括JDBC驱动、JNDI、连接池和嵌入式数据源的使用,以及如何通过不同类型的DataSourceBean进行数据库连接设置。
972

被折叠的 条评论
为什么被折叠?



