抽取SqlSessionFactoryUtils工具类,共享SqlSessionFactory创建过程
/** * SqlSessionFactory工具类 * @author:Mr.Tan * @Create:2018-10-30-23-14 **/public class SqlSessionFactoryUtils { private static SqlSessionFactory sqlSessionFactor; static { try { //创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder ssfb=new SqlSessionFactoryBuilder(); //创建核心配置文件的输入流 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); //通过输入流创建SqlSessionFactor对象 sqlSessionFactor=ssfb.build(inputStream); } catch (IOException e) { e.printStackTrace(); } } /** * 获取SqlSessionFactory * @return */ public static SqlSessionFactory getSqlSessionFactor() { return sqlSessionFactor; } public static void setSqlSessionFactor(SqlSessionFactory sqlSessionFactor) { SqlSessionFactoryUtils.sqlSessionFactor = sqlSessionFactor; }}
根据用户ID查询用户信息
修改 映射文件与sql
@Test public void testGetUserByUserName(){ //获取SqlSessionFactory SqlSessionFactory sqlSessionFactor= SqlSessionFactoryUtils.getSqlSessionFactor(); //创建sqlSession对象 SqlSession sqlSession=sqlSessionFactor.openSession(); // Listlist=sqlSession.selectList("user.getUserByUserName","%张%"); List list=sqlSession.selectList("user.getUserByUserName","张"); for(User user:list){ System.out.println(user); } //释放资源 sqlSession.close(); }