sqlSessionFactory是线程安全,只要创建一次
单个数据库映射关系经过编译后的内存镜像,用于创建Session
SqlSession其主要的作用是执行持久化操作
每一个线程都应该有一个自己的SqlSession实例
使用完SqlSession对象后要及时关闭
解决重复代码问题,提取相同功能的代码,编入同一个类中
static{}静态代码块 只执行一次
mybatis-config.xml代码优化
元素 是一个配置属性元素,该元素通常用来将内部
的配置外在化 4,即通过外部的配置来动态替换内部定义的苏醒
步骤代码:
创建con.test.utils包
创建MybatisUtils类:
package com.test.utils;
import java.io.IOException;
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 {
private static SqlSessionFactory sqlSessionFactory = null;
static{
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//2根据配置文件构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
MybatisTest:
@Test
public void findCustomerByIdTest() throws IOException{
//1.读取配置文件
//String resource = "mybatis-config.xml";
//InputStream inputStream = Resources.getResourceAsStream(resource);
//2根据配置文件构建SqlSessionFactory
//SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//SqlSession sqlsession = sqlSessionFactory.openSession();
//3.sqlsession执行映射文件中的SQL,并返回映射结果
//Customer customer =sqlsession.selectOne("com.test.mapper.CustomerMapper.findCustomerById",1);
SqlSession sqlsession = MybatisUtils.getSession();
CustomerMapper customerMapper=sqlsession.getMapper(CustomerMapper.class);
Customer customer = customerMapper.findCustomerById(1);
System.out.println(customer.toString());
//4.关闭sqlsession
sqlsession.close();
}
src下创建文件db.properties:
driver = com.microsoft.sqlserver.jdbc.SQLServerDriver url = jdbc:sqlserver://127.0.0.1:1433;DatabaseName=mybatis username = sa password = ###
mybatis-config:



