1. 程式人生 > >Mybatis配置C3p0 和Druid連線池

Mybatis配置C3p0 和Druid連線池

普通java工程配置Mybatis 連線池

整體結構
在這裡插入圖片描述

匯入jar 包:

連結:https://pan.baidu.com/s/1aEpDPO9xRK1_shVsUpOEZA
提取碼:16nf

Mybatis 配置檔案:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 引入資料庫連線配置檔案 --> <properties resource="main/resource/db.properties"></properties> <settings> <!-- 設定駝峰命名規則 將資料庫的欄位jj_kk 自動對映到POJO 的jjKk 屬性 --> <!-- 設定org.apache.ibatis.session.Configuration 的屬性 mapUnderscoreToCamelCase--> <setting name="mapUnderscoreToCamelCase"
value="true"/> <!-- 獲取自增主鍵 全域性配置 但是insert中還是要配 keyProperty="id" --> <!-- <setting name="useGeneratedKeys" value="true"/> --> </settings> <!-- 定義類的別名 --> <typeAliases> <!-- 在對映檔案中使用別名 --> <typeAlias type="com.feifan.pojo.User" alias="User"
/> <!-- 多個類,可以通過配置包掃描 預設別名為類名 --> <package name="com.feifan.pojo"/> </typeAliases> <!-- 多個 開發環境,測試環境,選擇開發環境 --> <environments default="production"> <environment id="development"> <!--決定事務作用域和控制方式的事務管理器(TransactionManager) --> <transactionManager type="JDBC"></transactionManager> <!-- 資料來源採用連線池POOLED/UNPOOLED --> <dataSource type="POOLED"> <property name="driver" value="${jdbcDriver}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${jdbcUser}"/> <property name="password" value="${jdbcPassword}"/> </dataSource> </environment> <!-- 測試環境 C3P0連線池 --> <environment id="test"> <transactionManager type="JDBC"></transactionManager> <dataSource type="com.feifan.pojo.c3p0DatasourceFactory"> <property name="driverClass" value="${jdbcDriver}"/> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="user" value="${jdbcUser}"/> <property name="password" value="${jdbcPassword}"/> <property name="initialPoolSize" value="5"/> <property name="maxPoolSize" value="20"/> <property name="minPoolSize" value="5"/> </dataSource> </environment> <!-- 生產環境 --> <environment id="production"> <transactionManager type="JDBC"></transactionManager> <dataSource type="com.feifan.pojo.DruidDataSourceFactory"> <property name="driverClassName" value="${jdbcDriver}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${jdbcUser}"/> <property name="password" value="${jdbcPassword}"/> </dataSource> </environment> </environments> <!-- 定義對映檔案 --> <mappers> <!-- sql對映檔案的路徑 --> <!-- <mapper resource="com/feifan/mapper/UserMapper.xml"/> <mapper resource="com/feifan/mapper/tbUserMapper.xml"/> --> <!-- 也可以通過配置介面的包掃描,但是xml檔案路徑要和介面的包路徑一樣--> <package name="com.feifan.mapper"/> </mappers> </configuration>

在這裡插入圖片描述

資料庫連結資訊:

db.proterties

jdbcDriver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/chat
jdbcUser=root
jdbcPassword=root

檢視sql 執行日誌log4j.properties:

log報錯 因為log4j.properties檔案的路徑不在主路徑下面:

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

這種情況下沒有打印出日誌, 說明應用並沒有對log4j進行初始化. 解決方法是要在應用啟動時就進行

PropertyConfigurator.configure("src/main/resource/log4j.properties");

配置:

log4j.rootLogger=info,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} %d %p [%c] -%m%n  

# 列印sql語句:debug; 執行結果:trace
## 指定mapper配置檔案中的namespace
#com.feifan.mapper.UserMapper 單個介面
#com.feifan.mapper包下面所有的
log4j.logger.com.feifan.mapper =TRACE

效果:

2018-11-10 18:04:51 2018-11-10 18:04:51,067 DEBUG [com.feifan.mapper.UserMapper.findUser] -==>  Preparing: select * from t_user where id=? and email=? 
  2018-11-10 18:04:51 2018-11-10 18:04:51,068 DEBUG [com.feifan.mapper.UserMapper.findUser] -==> Parameters: 2(Integer), 9090(String)
  2018-11-10 18:04:51 2018-11-10 18:04:51,069 TRACE [com.feifan.mapper.UserMapper.findUser] -<==    Columns: id, age, create_who, email, gender, name, pw, signtime
  2018-11-10 18:04:51 2018-11-10 18:04:51,069 TRACE [com.feifan.mapper.UserMapper.findUser] -<==        Row: 2, 10, dd, 9090, null, 二狗子, null, null
  2018-11-10 18:04:51 2018-11-10 18:04:51,070 DEBUG [com.feifan.mapper.UserMapper.findUser] -<==      Total: 1

兩個POJO類:

TbUser類:

public class TbUser implements Serializable {
	private Integer id;
	private String name;
	private String pw;
	private Integer age;
	private String email;
	private String gender;
	private Date signTime;}

User類:

public class User  implements Serializable{
	private Integer id;
	private Integer age;
	private String createWho;
	private String email;
	private String gender;
	private String name;
	private String pw;
	private Date signtime;
	}

獲取Sqlsession 工具類:

import java.io.IOException;
import java.io.InputStream;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
	
	private  static SqlSessionFactory sqlSessionFactory=null;
	private  MybatisUtils() {}
	
	static{
		String resource="main/resource/MybatisConfig.xml";
		try {
			//讀取配置檔案 獲取sqlsessionFactory
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			Configuration configuration = sqlSessionFactory.getConfiguration();
			System.out.println(configuration);
			Environment environment = configuration.getEnvironment();
			System.out.println(environment);
			DataSource dataSource = environment.getDataSource();
			System.out.println(dataSource);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 獲取sqlSession
	 * @return
	 */
	public static SqlSession getSqlSession(){
		SqlSession sqlSession = sqlSessionFactory.openSession();
		return sqlSession;
	}

}

整合c3p0/Druid連線池:

Mybatis 沒有幫開發者實現 c3p0 資料庫連線池,故需要使用者自己實現 c3p0 來載入資料連線池。其實很簡單的,只要繼承 UnpooledDataSourceFactory 並把 dataSource 實現。我們的 mybatis 就實現了 c3p0 資料庫連線池。
C3p0連線池

import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/** Mybatis 沒有幫開發者實現 c3p0 資料庫連線池,
 * 故需要使用者自己實現 c3p0 來載入資料連線池
 * 。其實很簡單的,只要繼承 UnpooledDataSourceFactory 並把 dataSource 實現。
 * 我們的 mybatis 就實現了 c3p0 資料庫連線池。*/
public class c3p0DatasourceFactory  extends UnpooledDataSourceFactory{
	public c3p0DatasourceFactory() {
		this.dataSource=new ComboPooledDataSource();
	}
}

Druid連線池

import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

import com.alibaba.druid.pool.DruidDataSource;

public class DruidDataSourceFactory  extends UnpooledDataSourceFactory{
	public DruidDataSourceFactory() {
		this.dataSource=new DruidDataSource();
	}
}

介面檔案:

import com.feifan.pojo.TbUser;
public interface TbUserMapper {
	TbUser selectById(Integer id);
}

UserMapper介面:

import org.apache.ibatis.annotations.Param;
import com.feifan.pojo.User;

public interface UserMapper {
	User selectById(Integer id);
	
	int insertUser(User user);
	
	void insertUserTwo(User user);
	
	/**多個引數可以使用集合的 方式傳遞,map等*/
	User findUser(@Param("id")Integer id,@Param("email") String email);
}

sql對映檔案:

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace 介面全名 -->
<mapper namespace="com.feifan.mapper.UserMapper">

	<!-- statement --> 
	<select id="selectById" parameterType="int" resultType="User" >
		SELECT * FROM t_user where id=#{id}
	</select>
	
	<!-- 通過useGeneratedKeys="true"  keyProperty="id" 獲取剛剛插入的自增主鍵id, keyProperty="id
	 並把賦值給物件的屬性id
	 -->
	<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id" >
		insert into t_user(email,signtime)values(#{email},#{signtime})
	</insert>
	
	<!-- 方式二 獲取剛剛插入的自增主鍵id  -->
	<insert id="insertUserTwo" parameterType="User" useGeneratedKeys="true">
		<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
			SELECT LAST_INSERT_ID()
		</selectKey>
		insert into t_user(email,signtime)values(#{email},#{signtime})
	</insert>
	
	<select id="findUser" resultType="User">
		select * from t_user where id=#{id} and email=#{email}
	</select>

</mapper>

TbUserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace 介面全名 -->
<mapper namespace="com.feifan.mapper.TbUserMapper">

	<!-- statement --> 
	<select id="selectById" parameterType="int" resultType="TbUser" >
		SELECT * FROM tb_user where id=#{id}
	</select>
</mapper>

新增資料後,獲取自增主鍵的值:

方式1:

<!-- 通過useGeneratedKeys="true"  keyProperty="id" 獲取剛剛插入的自增主鍵id, keyProperty="id
	 並把賦值給物件的屬性id
	 -->
	<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id" >
		insert into t_user(email,signtime)values(#{email},#{signtime})
	</insert>

方式二:

<!-- 方式二 獲取剛剛插入的自增主鍵id  -->
	<insert id="insertUserTwo" parameterType="User" useGeneratedKeys="true">
		<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
			SELECT LAST_INSERT_ID()
		</selectKey>
		insert into t_user(email,signtime)values(#{email},#{signtime})
	</insert>

測試類:

public class TestMybatis {
	
	public static void main(String[] args) {
		new TestMybatis().testSelectById();
		new TestMybatis().insertGetId();
	}

	public void insertGetId(){
		User user=new User();
		/** 向資料庫中增加資料 */
		SqlSession sqlSession3 = MybatisUtils.getSqlSession();
		UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);
		user.setEmail("94201435");
		user.setSigntime(new Date());
		System.err.println(user);
		userMapper3.insertUserTwo(user);
		sqlSession3.commit();//預設事務關閉,需要手動提交事務
		sqlSession3.close();
		System.out.println(user.getId());
		System.out.println();
	}
	
	@Test
	public void testSelectById(){
		//簡單工程log4j 屬性檔案 需要使用載入此屬性檔案
		PropertyConfigurator.configure("src/main/resource/log4j.properties");
		
		/**使用介面方式 查詢資料庫*/
		SqlSession sqlSession = MybatisUtils.getSqlSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = userMapper.selectById(2);
		System.out.println(user);
		System.out.println();
		
		/** 使用一般的方式查詢資料庫  名稱空間+方法名 ,引數*/
		Object one = sqlSession.selectOne("com.feifan.mapper.UserMapper.selectById", 2);
		System.out.println(((User)one).toString());
		System.out.println();
		
		/** 向資料庫中增加資料 */
		SqlSession sqlSession3 = MybatisUtils.getSqlSession();
		UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);
		user.setEmail("94201435");
		user.setSigntime(new Date());
		System.err.println(user);
		userMapper3.insertUser(user);
		sqlSession3.commit();//預設事務關閉,需要手動提交事務
		System.out.println(user.getId());
		System.out.println();
		
		/** 多個引數傳遞 查詢*/
		User findUser = userMapper.findUser(2, "9090");
		System.out.println(findUser);
		System.out.println();
		
		/** 查詢另外一個表 */
		SqlSession sqlSession2 = MybatisUtils.getSqlSession();
		TbUserMapper tbUserMapper = sqlSession.getMapper(TbUserMapper.class);
		TbUser tbUser = tbUserMapper.selectById(2);
		System.out.println(tbUser);
		sqlSession.close();
		sqlSession2.close();
	}
	
	
}

輸出結果:

[email protected]
[email protected]
{
	CreateTime:"2018-11-10 18:04:50",
	ActiveCount:0,
	PoolingCount:0,
	CreateCount:0,
	DestroyCount:0,
	CloseCount:0,
	ConnectCount:0,
	Connections:[
	]
}
2018-11-10 18:04:50 2018-11-10 18:04:50,782 INFO [com.alibaba.druid.pool.DruidDataSource] -{dataSource-1} inited
  Sat Nov 10 18:04:50 CST 2018 WARN: Establishing SSL connection without server's identity verification is n