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();
	}
	
	
}

输出结果:

org.apache.ibatis.session.Configuration@3327bd23
org.apache.ibatis.mapping.Environment@4e1d422d
{
	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 not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-11-10 18:04:50 2018-11-10 18:04:50,995 DEBUG [com.feifan.mapper.UserMapper.selectById] -==>  Preparing: SELECT * FROM t_user where id=? 
  2018-11-10 18:04:51 2018-11-10 18:04:51,024 DEBUG [com.feifan.mapper.UserMapper.selectById] -==> Parameters: 2(Integer)
  2018-11-10 18:04:51 2018-11-10 18:04:51,040 TRACE [com.feifan.mapper.UserMapper.selectById] -<==    Columns: id, age, create_who, email, gender, name, pw, signtime
  2018-11-10 18:04:51 2018-11-10 18:04:51,041 TRACE [com.feifan.mapper.UserMapper.selectById] -<==        Row: 2, 10, dd, 9090, null, 二狗子, null, null
  2018-11-10 18:04:51 2018-11-10 18:04:51,044 DEBUG [com.feifan.mapper.UserMapper.selectById] -<==      Total: 1
  User [id=2, age=10, createWho=dd, email=9090, gender=null, name=二狗子, pw=null, signtime=null]

User [id=2, age=10, createWho=dd, email=9090, gender=null, name=二狗子, pw=null, signtime=null]

User [id=2, age=10, createWho=dd, email=94201435, gender=null, name=二狗子, pw=null, signtime=Sat Nov 10 18:04:51 CST 2018]
Sat Nov 10 18:04:51 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-11-10 18:04:51 2018-11-10 18:04:51,052 DEBUG [com.feifan.mapper.UserMapper.insertUser] -==>  Preparing: insert into t_user(email,signtime)values(?,?) 
  2018-11-10 18:04:51 2018-11-10 18:04:51,055 DEBUG [com.feifan.mapper.UserMapper.insertUser] -==> Parameters: 94201435(String), 2018-11-10 18:04:51.045(Timestamp)
  2018-11-10 18:04:51 2018-11-10 18:04:51,063 DEBUG [com.feifan.mapper.UserMapper.insertUser] -<==    Updates: 1
  45

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
  User [id=2, age=10, createWho=dd, email=9090, gender=null, name=二狗子, pw=null, signtime=null]

2018-11-10 18:04:51 2018-11-10 18:04:51,071 DEBUG [com.feifan.mapper.TbUserMapper.selectById] -==>  Preparing: SELECT * FROM tb_user where id=? 
  2018-11-10 18:04:51 2018-11-10 18:04:51,071 DEBUG [com.feifan.mapper.TbUserMapper.selectById] -==> Parameters: 2(Integer)
  2018-11-10 18:04:51 2018-11-10 18:04:51,072 TRACE [com.feifan.mapper.TbUserMapper.selectById] -<==    Columns: ID, name, pw, age, email, gender, sign_time
  2018-11-10 18:04:51 2018-11-10 18:04:51,072 TRACE [com.feifan.mapper.TbUserMapper.selectById] -<==        Row: 2, b, b, null, b, ?, 2018-07-08 20:03:12.0
  2018-11-10 18:04:51 2018-11-10 18:04:51,073 DEBUG [com.feifan.mapper.TbUserMapper.selectById] -<==      Total: 1
  TbUser [id=2, name=b, pw=b, age=null, email=b, gender=?, signTime=Sun Jul 08 20:03:12 CST 2018]
User [id=null, age=null, createWho=null, email=94201435, gender=null, name=null, pw=null, signtime=Sat Nov 10 18:04:51 CST 2018]
2018-11-10 18:04:51 2018-11-10 18:04:51,073 DEBUG [com.feifan.mapper.UserMapper.insertUserTwo] -==>  Preparing: insert into t_user(email,signtime)values(?,?) 
  2018-11-10 18:04:51 2018-11-10 18:04:51,074 DEBUG [com.feifan.mapper.UserMapper.insertUserTwo] -==> Parameters: 94201435(String), 2018-11-10 18:04:51.073(Timestamp)
  2018-11-10 18:04:51 2018-11-10 18:04:51,075 DEBUG [com.feifan.mapper.UserMapper.insertUserTwo] -<==    Updates: 1
  2018-11-10 18:04:51 2018-11-10 18:04:51,075 DEBUG [com.feifan.mapper.UserMapper.insertUserTwo!selectKey] -==>  Preparing: SELECT LAST_INSERT_ID() 
  2018-11-10 18:04:51 2018-11-10 18:04:51,075 DEBUG [com.feifan.mapper.UserMapper.insertUserTwo!selectKey] -==> Parameters: 
  2018-11-10 18:04:51 2018-11-10 18:04:51,075 TRACE [com.feifan.mapper.UserMapper.insertUserTwo!selectKey] -<==    Columns: LAST_INSERT_ID()
  2018-11-10 18:04:51 2018-11-10 18:04:51,075 TRACE [com.feifan.mapper.UserMapper.insertUserTwo!selectKey] -<==        Row: 46
  2018-11-10 18:04:51 2018-11-10 18:04:51,076 DEBUG [com.feifan.mapper.UserMapper.insertUserTwo!selectKey] -<==      Total: 1
  46

猜你喜欢

转载自blog.csdn.net/qq_16183731/article/details/83931933