1.创建模板,mapper文件模板和mybatis主配置文件模板
点击new 有模板内容
工具类
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();
}
}
//创建方法获取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();
}
}