zoukankan      html  css  js  c++  java
  • 使用Map接收返回数据库的数据

    查询返回值是map类型的一条数据

    1 首先在接口中写方法

    public interface EmployeeMapper {

    //返回一条记录的map;key就是列名,值就是对应的值
    public Map<String, Object> getEmpByIdReturnMap(Integer id);

    }

    2 在映射文件xml配置方法

    <!--public Map<String, Object> getEmpByIdReturnMap(Integer id); -->
    <select id="getEmpByIdReturnMap" resultType="map">
    select * from tbl_employee where id=#{id}
    </select>

    3在junit方法里进行测试

    @Test
    public void test04() throws IOException{

    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    //1、获取到的SqlSession不会自动提交数据
    SqlSession openSession = sqlSessionFactory.openSession();

    try{
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
    Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
    System.out.println(map);
    String email=(String) map.get("email");
    System.out.println(email);
    }finally{
    openSession.close();
    }
    }

    查询返回值是map类型的多条数据

    1 首先在接口中写方法

    public interface EmployeeMapper {

    //多条记录封装一个map:Map<Integer,Employee>:键是这条记录的主键,值是记录封装后的javaBean
    //@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key

    @MapKey("email")
    public Map<String, Employee> getEmpByLastNameLikeReturnMap(String email);

    }

    2 在映射文件xml配置方法


    <!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName); -->
    <select id="getEmpByLastNameLikeReturnMap" resultType="com.atguigu.mybatis.bean.Employee">
    select * from tbl_employee where email like #{email}
    </select>

    3在junit方法里进行测试

    @Test
    public void test04() throws IOException{

    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    //1、获取到的SqlSession不会自动提交数据
    SqlSession openSession = sqlSessionFactory.openSession();

    try{
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
    Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%e%");
    System.out.println(map);
    System.out.println("第一条记录为:"+map.get("jerry6@atguigu.com"));
    System.out.println("第一条记录为:"+map.get("jerry6@atguigu.com").getEmail());

    }finally{
    openSession.close();
    }
    }

  • 相关阅读:
    PTA乙级 (1058 选择题 (20分))
    PTA乙级 (1059 C语言竞赛 (20分)(map.find()、vector中的find))
    Ubuntu18.04之vim安装及配置
    PTA乙级 (1060 爱丁顿数 (25分))
    C++实现求N个数的最大公约数和最小公倍数
    PTA乙级 (1062 最简分数 (20分))
    PTA乙级 (1065 单身狗 (25分)(map,set.find(),vector))
    PTA乙级 (1067 试密码 (20分))
    ionic build android--> Build failed with an exception. Execution failed for task ':processDebugResources'.
    Http-Only Cookie
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8545490.html
Copyright © 2011-2022 走看看