MyBatis 工具类抽取
之前的MyBatis入门程序,可以发现测试类的代码有部分是重复的,这时可以抽取出一个MyBatisUtils工具类来简化代码。
package com.yiidian.utils;
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;
/**
* 工具类
*一点教程网 - www.yiidian.com
*/
public class MyBatisUtils {
private static SqlSessionFactoryBuilder builder;
private static SqlSessionFactory factory;
/**
* 初始化SqlSessionFactory
*/
static {
try {
builder = new SqlSessionFactoryBuilder();
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
factory = builder.build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取sqlSession
*/
public static SqlSession getSession(){
return factory.openSession();
}
}
测试类可以重构成以下写法:
package com.yiidian.mybatis;
import com.yiidian.dao.CustomerDao;
import com.yiidian.domain.Customer;
import com.yiidian.utils.MyBatisUtils;
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;
import java.util.List;
/**
* MyBatis测试类
* 一点教程网 - www.yiidian.com
*/
public class TestCustomerDao2 {
public static void main(String[] args) throws Exception {
//1.创建SqlSession
SqlSession sqlSession = MyBatisUtils.getSession();
//2.生成Dao接口代理对象
CustomerDao userDao = sqlSession.getMapper(CustomerDao.class);
//3.执行Dao接口方法
List<Customer> list = userDao.findAll();
for(Customer c:list){
System.out.println(c);
}
//4.释放资源
sqlSession.close();
}
}
热门文章
优秀文章