配置数据源
配置myBatisConfig.xml全局配置文件
<?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="db.properties"></properties>
<!-- 配置类的别名(配置完后,别名就是类名) 注意:这里的配置不能放在后面,否则会出错无效 -->
<typeAliases>
<package name="com.mingde.po"/>
</typeAliases>
<!-- 配置开发环境 -->
<environments default="development">
<environment id="development">
<!-- 配置事务管理器 -->
<transactionManager type="JDBC" />
<!-- 配置数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 配置sql语句映射文件 (以下可以2种一起配置)-->
<mappers>
<!-- 引用Empmapper.xml映射文件 -->
<mapper resource="com/mingde/mapper/Empmapper.xml" />
<!-- 引用映射sql语句注解的类 -->
<mapper class="com.mingde.dao.EmpDao" />
</mappers>
</configuration>
配置MyBatisUtils(配置SqlSessionFactory)
package com.mingde.utils;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtils {
//获取资源文件,创建SqlSessionFactory工厂
public static SqlSessionFactory getSqlSessionFactory()throws Exception{
InputStream inputStream = Resources.getResourceAsStream("myBatisConfig.xml");
return new SqlSessionFactoryBuilder().build(inputStream);
}
//打开SqlSessoinFactory工厂,获取Sqlsession
public static SqlSession getSqlSession()throws Exception{
return getSqlSessionFactory().openSession();
}
//打开SqlSessoinFactory工厂,获取Sqlsession,并且自动提交commit;
public static SqlSession getSqlSessionAutoCommit()throws Exception{
//注意:如果为true,则进增删改时,会自动commit提交,如果不写或为false的话则不会自动commit提交,则需要在写完增删改之后,session.commmit();
return getSqlSessionFactory().openSession(true);
}
}