LD is tigger forever,CG are not brothers forever, throw the pot and shine forever. Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people. talk is cheap, show others the code and KPI, Keep progress,make a better result. Survive during the day and develop at night。
目录
概 述
1.database 数据源: 通常有3种方法: 1、mybatis中的数据源 mybatis连接池为我们提供了3种?式的配置:
- POOLED:采?传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
- UNPOOLED:采?传统的获取连接的?式,虽然也实现Javax.sql.DataSource接?,但是并没有使?池的思想。
- JNDI:采?服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不?样。
注意:如果不是web或者maven的war?程,JNDI是不能使?的。 2、在mybatis中配置数据源 2.1、POOLED数据源的配置?式
测试代码:
@Test
void testNetworkTimeout_PooledDataSource() throws Exception {
UnpooledDataSource unpooledDataSource = (UnpooledDataSource) PgContainer.getUnpooledDataSource();
PooledDataSource dataSource = new PooledDataSource(unpooledDataSource);
dataSource.setDefaultNetworkTimeout(5000);
try (Connection connection = dataSource.getConnection()) {
assertEquals(5000, connection.getNetworkTimeout());
}
}
2.2、UNPOOLED数据源的配置?式
测试代码:
@Test
void shouldNotRegisterTheSameDriverMultipleTimes() throws Exception {
UnpooledDataSource dataSource = null;
dataSource = new UnpooledDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:multipledrivers", "sa", "");
dataSource.getConnection().close();
int before = countRegisteredDrivers();
dataSource = new UnpooledDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:multipledrivers", "sa", "");
dataSource.getConnection().close();
assertEquals(before, countRegisteredDrivers());
}
2.3、JNDI数据源的配置?式 将数据源的配置?件 context.xml 放到?程的webapp/META-INF/下 context.xml <Resource name="jdbc/mybatis"数据源的名称 type="javax.sql.DataSource"数据源类型 auth="Container"数据源提供者 maxActive="20"最?活动数 maxWait="10000"最?等待时间 maxIdle="5"最?空闲数 username="root"?户名 password="1234"密码 driverClassName="com.mysql.jdbc.Driver"驱动类 url="jdbc:mysql://localhost:3306/mybatis"连接url字符串 /> 然后在mybatis的主配置?件中配置数据源,其中前缀"java:comp/env/ "是固定的,后缀 “jdbc/mybatis” 是在context.xml中取的JNDI数据源名 称 </dataSourc
测试代码:
@Test
void shouldRetrieveDataSourceFromJNDI() {
createJndiDataSource();
JndiDataSourceFactory factory = new JndiDataSourceFactory();
factory.setProperties(new Properties() {
{
setProperty(JndiDataSourceFactory.ENV_PREFIX + Context.INITIAL_CONTEXT_FACTORY, TEST_INITIAL_CONTEXT_FACTORY);
setProperty(JndiDataSourceFactory.INITIAL_CONTEXT, TEST_INITIAL_CONTEXT);
setProperty(JndiDataSourceFactory.DATA_SOURCE, TEST_DATA_SOURCE);
}
});
DataSource actualDataSource = factory.getDataSource();
assertEquals(expectedDataSource, actualDataSource);
}
使用字符串建立一个factory ,通过JNDI找到对应的数据源。
小结
参考资料和推荐阅读
1.链接: link.
|