1.創(chuàng)建模板肋联,mapper文件模板和mybatis主配置文件模板
點擊new 有模板內(nèi)容
工具類
package com.zwx.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;
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
static {
String config = "mybatiszhu.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(config);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//創(chuàng)建方法獲取sqlsession對象
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
if (sqlSessionFactory !=null){
sqlSession=sqlSessionFactory.openSession();
}
return sqlSession;
}
}
測試類
public class Mytest {
@Test
public void testSelectById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
String sqlId ="com.zwx.dao.StudentDao"+"."+"selectById";
Student student = sqlSession.selectOne(sqlId,1002);
System.out.println(student);
sqlSession.close();
}
}