赞
踩
一、问题
对于任何和数据库交互的框架,都会涉及会话、链接、事务,了解它们各自的概念及相互关系对于理解框架以及参数配置优化都有很大好处。MyBatis是工作中使用较多的数据库层解决方案,我们有必要对会话、链接、事务进行深入了解一下。
二、项目配置
我们使用的样例项目的配置如下:
/p>
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
测试代码如下:
package com.iwill.mybatis;
import com.iwill.mybatis.dao.mapper.ext.UserMapperExt;
import com.iwill.mybatis.dao.model.UserDTO;
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.InputStream;
public class MyBatisTest {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession1 = sqlSessionFactory.openSession();
UserMapperExt userMapperExt1 = sqlSession1.getMapper(UserMapperExt.class);
userMapperExt1.insert(new UserDTO("houliu",23));
userMapperExt1.findUserListByName("zhangsan");
userMapperExt1.update("name" ,"wangwu",22);
sqlSession1.commit();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
UserMapperExt userMapperExt2 = sqlSession2.getMapper(UserMapperExt.class);
userMapperExt2.insert(new UserDTO("houliu",23));
userMapperExt2.findUserListByName("zhangsan");
userMapperExt2.update("name" ,"wangwu",22);
sqlSession2.commit();
}
}
三、会话
会话是MyBatis执行SQL的基础,MyBatis中的会话是SqlSession,默认实现是DefaultSqlSession。可以通过SqlSessionFactory的openSession来获取的。
通过SqlSessionFactory获取SqlSession的代码如下:
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
流程图如下:
1、在第一步中,通过new SqlSessionFactoryBuilder().build(inputStream)来构造SqlSessionFactory,参数是配置文件的输入流。
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。