<?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>
<!-- 引用db.properties配置文件 -->
<properties resource="jdbc.properties"></properties>
<!--
development : 开发模式
work : 工作模式
-->
<typeAliases>
<!--别名-->
<!--<typeAlias alias="User" type="com.mybatis.model.User"/>-->
<!--批量别名,别名就是类名-->
<package name="com.mybatis.model"></package>
</typeAliases>
<environments default="development">
<environment id="development">
<!--使用jdbc事务管理,事物是由mybatis控制-->
<transactionManager type="JDBC"/>
<!--配置数据源 type POOLED UNPOLLED JNDI(Tomcat) -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<!--<property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!--<property name="url" value="jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf8&useSSL=true"/>-->
<!--<property name="username" value="root"/>-->
<!--<property name="password" value="186"/>-->
</dataSource>
</environment>
</environments>
<mappers>
<!--这三种都可以-->
<!--注明xml文件位置-->
<!--<mapper resource="com/mybatis/mapper/UserMapper.xml"/>-->
<mapper class="com.mybatis.mapper.UserMapper"></mapper>
<!--这种是写包-->
<!--<package name="com.mybatis.mapper"/>-->
</mappers>
</configuration>
引入的jdbc.properties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=186
编写一个mybatisUtil文件
package com.mybatis.util;/**
* Created by matengbing on 2018/9/26.
*/
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 java.io.IOException;
import java.io.InputStream;
/**
* @program: 9.26mybatis
* @description:
* @author: matb
* @create: 2018-09-26 14:46
**/
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
private MybatisUtil() {
}
private static SqlSessionFactory getSqlSessionFactory() {
/*
* 使用单例模式获取
* */
String configPath="mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(configPath);
if(sqlSessionFactory==null){
synchronized (MybatisUtil.class){
if(sqlSessionFactory==null){
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return sqlSessionFactory;
}
public static SqlSession getSession(){
return getSqlSessionFactory().openSession();
}
}