在pom.xml加入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
工作流程:读取配置文件,创建工厂对象(SqlSessionFactory),打开Session,根据SQL的id查找对应的MapperStatement对象,持久化操作,将查询对象映射成对应的对象,关闭资源
一配置文件
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/witkey_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
二测试连接
@Test
public void connectTest() {
String resource = "mybatis-config.xml";
InputStream is = null;
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
System.out.println(sqlSession.getConnection());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
创建Mabatis工具类
public class MybatisUtil {
private static String CONFIG_FILE_LOCAL = "mybatis-config.xml";
private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<SqlSession>();
private static InputStream inputStream;
private static SqlSessionFactory sqlSessionFactory;
static{
try {
inputStream = Resources.getResourceAsStream(CONFIG_FILE_LOCAL);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
SqlSession sqlSession = THREAD_LOCAL.get();
if(sqlSession==null){
sqlSession = (sqlSessionFactory!=null)?sqlSessionFactory.openSession():null;
THREAD_LOCAL.set(sqlSession);
}
return sqlSession;
}
public static void closeSqlSession(){
SqlSession sqlSession = THREAD_LOCAL.get();
THREAD_LOCAL.set(null);
if(sqlSession != null){
sqlSession.close();
}
}
}
网友评论