Mybatis 31_数据源配置及配置第三方数据源 项目0405内置数据源 项目0406C3P0数据源

31_数据源配置及配置第三方数据源

  • 数据源配置
    • MyBatis内置了三个数据源工厂的实现类
    • 配置数据源时,该数据源实现类有什么setter方法,此时就可以配置对应的属性:
    • 配置使用第三方数据源,比如C3P0之类?
      • 项目0405内置数据源
      • 项目0406C3P0数据源

数据源配置

事务管理器属于数据库环境的配置,因此它放在元素中,
通过的type属性来配置:
该属性值应该指定为数据源工厂的实现类的完整类名

MyBatis内置了三个数据源工厂的实现类

  • JndiDataSourceFactory(JNDI):要使用容器管理的数据源。
  • PooledDataSourceFactory(POOLED):使用MyBatis内置的数据源
  • UnpooledDataSourceFactory(UNPOOLED):使用MyBatis内置的、不带连接池数据源。
    配置数据源时配置的这些property将直接对应于数据源实现类的setter方法。

配置数据源时,该数据源实现类有什么setter方法,此时就可以配置对应的属性:

  • defaultAutoCommit(setDefaultAutoCommit)事务是否自动提交
  • defaultNetworkTimeout(setDefaultNetworkTimeout)配置超时
  • defaultTransactionIsolationLevel(setDefaultTransactionIsolationLevel)配置事务的隔离级别
    项目0405内置数据源

配置使用第三方数据源,比如C3P0之类?

只要两步:
(1) 开发自定义的数据源工厂,必须实现DataSourceFactory接口
通常建议继承UnpooledDataSourceFactory类来实现,这样会更方便,
然后为该工厂类提供一个构造器,并在构造器中初始化dataSource成员变量即可。
(2)在mybatis-config.xml中通过dataSource…/>的type属性指定自定义的DataSourceFactory实现类
项目0406C3P0数据源

项目0405内置数据源

主配置文件 (POOLED):使用MyBatis内置的数据源


DOCTYPE configuration
	PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
	
<configuration>

 	<typeAliases>
 		
 		<package name="org.itcheng.app.domain"/>
 	typeAliases>
 	
	
	<environments default="mysql">
		
		<environment id="mysql">
			
			<transactionManager type="JDBC" />
			
			<dataSource type="POOLED">
				
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC" />
				<property name="username" value="root" />
				<property name="password" value="root" />
				
				<property name="poolMaximumActiveConnections" value="45"/>
				
				<property name="poolMaximumIdleConnections" value="20"/>
			dataSource>
		environment>
	environments>
	<mappers>
		
		<mapper resource="org/itcheng/app/dao/NewsMapper.xml" />
	mappers>
configuration>

项目0406C3P0数据源

自定义数据源

package org.itcheng.app;

import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * Description:自定义数据源工厂
 * 
网站: 疯狂Java联盟 *
Copyright (C), 2001-2020, Yeeku.H.Lee *
This program is protected by copyright laws. *
Program Name: *
Date: * @author Yeeku.H.Lee [email protected] * @version 1.0 */
public class C3P0DataSourceFactory extends UnpooledDataSourceFactory { public C3P0DataSourceFactory() { // ComboPooledDataSource是C3P0的数据源的实现类 // 以后你要使用哪个数据源,你就在这里创建该数据源的实例即可。 this.dataSource = new ComboPooledDataSource(); } }

主配置文件


DOCTYPE configuration
	PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
	
<configuration>

 	<typeAliases>
 	    
 		<typeAlias type="org.itcheng.app.C3P0DataSourceFactory" alias="C3P0"/>
 		
 		<package name="org.itcheng.app.domain"/>
 	typeAliases>
 	
	
	<environments default="mysql">
		
		<environment id="mysql">
			
			<transactionManager type="JDBC" />
			
			<dataSource type="C3P0">
				
				<property name="driverClass" value="com.mysql.jdbc.Driver" />
				<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC" />
				<property name="user" value="root" />
				<property name="password" value="root" />
				
				<property name="maxPoolSize" value="40"/>
				
				<property name="minPoolSize" value="2"/>
				
				<property name="initialPoolSize" value="2"/>
				<property name="maxStatements" value="1000"/>
			dataSource>
		environment>
	environments>
	<mappers>
		
		<mapper resource="org/itcheng/app/dao/NewsMapper.xml" />
	mappers>

configuration>

主类

package lee;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.itcheng.app.dao.NewsMapper;
import org.itcheng.app.domain.News;

public class NewsManager
{
	// SqlSessionFactory应该是应用级别
	private static SqlSessionFactory sqlSessionFactory;
	public static void main(String[] args) throws IOException
	{
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 1. 创建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// 2. 打开SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
				
		// 查询消息
		selectNews(sqlSession);				
	}
	
	public static void selectNews(SqlSession sqlSession)
	{
		// 此处的NewsMapper只是一个接口
		// MyBatis会使用JDK的动态代理为Mapper接口生成实现类
		NewsMapper newsMapper = sqlSession.getMapper(NewsMapper.class);
		System.out.println(newsMapper.getClass());
		List<?> list = newsMapper.findNews(-1);
		
		System.out.println(list);
		
		// 4. 提交事务
		sqlSession.commit();
		// 5. 关闭资源
		sqlSession.close();	
		/* 结果
		 * 11月 23, 2023 2:01:53 下午 com.mchange.v2.log.MLog 
		 * 信息: MLog clients using java 1.4+ standard logging.
		 * 11月 23, 2023 2:01:53 下午 com.mchange.v2.c3p0.C3P0Registry 
		 * 信息: Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
		 * class com.sun.proxy.$Proxy18
		 * 11月 23, 2023 2:01:54 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource 
		 * 信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 1hge8gdaz1xkvkyjd0vy44|906d29b, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 1hge8gdaz1xkvkyjd0vy44|906d29b, idleConnectionTestPeriod -> 0, initialPoolSize -> 2, jdbcUrl -> jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 40, maxStatements -> 1000, maxStatementsPerConnection -> 0, minPoolSize -> 2, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {password=******, user=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
		 * DEBUG [main] org.itcheng.app.dao.NewsMapper.findNews ==>  Preparing: select news_id id, news_title title, news_content content from news_inf where news_id > ? 
		 * DEBUG [main] org.itcheng.app.dao.NewsMapper.findNews ==> Parameters: -1(Integer)
		 * DEBUG [main] org.itcheng.app.dao.NewsMapper.findNews <==      Total: 1
		 * [org.itcheng.app.domain.News@5471388b]
		 * 
		 * */
	}	
		
}

你可能感兴趣的:(mybatis,java,eclipse,mysql)