抽取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
<!--#{}相当于jdbc的?-->
<!--${}:字符串拼接指令,如果入参为普通数据类型{}内部职能写value-->
<!--如果返回结果为集合时,只需设置为每一个的数据类型--> <select id="getUserByUserName" parameterType="String" resultType="com.tanlei.newer.pojo.User"> <!--SELECT id,username,birthday,sex,address FROM user WHERE username LIKE #{name}--> SELECT id,username,birthday,sex,address FROM user WHERE username LIKE '%${value}%' </select>
@Test public void testGetUserByUserName(){ //获取SqlSessionFactory SqlSessionFactory sqlSessionFactor= SqlSessionFactoryUtils.getSqlSessionFactor(); //创建sqlSession对象 SqlSession sqlSession=sqlSessionFactor.openSession(); // List<User> list=sqlSession.selectList("user.getUserByUserName","%张%"); List<User> list=sqlSession.selectList("user.getUserByUserName","张"); for(User user:list){ System.out.println(user); } //释放资源 sqlSession.close(); }