一、返回list
mapper接口方法:
sqlmapper文件配置:
<!-- 根据name模糊查询返回list resultType写list里面的类型,多个结果mybatis会自动添加到list中 --> <select id="selectEmpByNameLike" resultType="employee"> select * from employee where name like #{name} </select>
测试方法:
@Test public void testSelectEmpByNameLike() throws IOException { String source = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(source); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); System.out.println(employeeMapper.selectEmpByNameLike("%o%")); sqlSession.close(); }
二、查询一个记录返回一个map
mapper接口方法:
sqlmapper文件配置
<!-- 返回一条记录的map;key就是列名,值就是对应列的值 查询结果只有一条时resultType的值为map,mybatis自动为许多java类型取了别名 --> <select id="selectEmpByIdReturnMap" resultType="map"> select * from employee where id = #{id} </select>
测试方法:
@Test public void testSelectEmpByIdReturnMap() throws IOException { String source = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(source); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); System.out.println(employeeMapper.selectEmpByIdReturnMap(1)); sqlSession.close(); }
三、查询多条记录返回一个map
mapper接口方法:
sqlmapper文件配置:
<!-- 返回多条记录的map;key为对应map接口方法中的@MapKey的值,值就是对应key的对象 查询结果为多条时resultType的值为返回对象的类型 --> <select id="selectEmpByNameLikeReturnMap" resultType="employee"> select * from employee where name like #{name} </select>
测试方法:
@Test public void testSelectEmpByNameLikeReturnMap() throws IOException { String source = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(source); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); System.out.println(employeeMapper.selectEmpByNameLikeReturnMap("%o%")); sqlSession.close(); }