• MyBatis-----4、MyBatis各种查询功能


    1、查询一个实体类对象

    若查询出的数据只有一条,可以通过实体类对象或者集合接收;
    若查询出的数据由多条,一定不能通过实体类对象进行结果的接收,此时会抛出异常,如:TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 5;可以通过List集合进行接收

    /*
        * 根据id查询用户信息
        * */
        User GetUserById(@Param("id") Integer id);
    
    • 1
    • 2
    • 3
    • 4
        <!--User GetUserById(@Param("id") Integer id);-->
        <select id="GetUserById" resultType="User">
            select * from t_user where id=#{id};
        </select>
    
    • 1
    • 2
    • 3
    • 4

    2、查询所有用户信息

        /*
        * 查询所有用户信息
        * */
        List<User> GetAllUser();
    
    • 1
    • 2
    • 3
    • 4
        <!--    List<User> GetAllUser();-->
        <select id="GetAllUser" resultType="User">
            select * from t_user;
        </select>
    
    • 1
    • 2
    • 3
    • 4

    3、查询表中数量信息

        /*
        查询用户信息的总记录数
        * */
        Integer getCount();
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
        <!--    Integer getCount();-->
        <select id="getCount" resultType="Integer">
            select count(*) from t_user;
        </select>
    
    • 1
    • 2
    • 3
    • 4

    4、根据id查询用户信息返回值为一个Map集合(一条语句)

        /*
        * 根据id查询用户信息返回值为一个Map集合
        * */
        Map<String,Object> getUserInMapById(@Param("id") Integer id);
    
    • 1
    • 2
    • 3
    • 4
        <!--Map<String,Object> getUserInMapById(@Param("id") Integer id);-->
        <select id="getUserInMapById" resultType="map">
            select * from t_user where id=#{id};
        </select>
    
    • 1
    • 2
    • 3
    • 4

    以查询id=3为例,其输出的结果为map集合:
    {password=123456, sex=?, id=3, age=23, email=12345@qq.com, username=admin}

    4、查询多条数据为一个map集合

    以查询所有用户信息为map集合为例:
    一条数据视为一个map集合,通过list嵌套map集合实现多条数据的查询,如下:

        /*
        * 查询所有用户信息为map集合,一个表中会有多条数据,一个map集合对应一条数据,因此还需将所有map集合放在list集合中
        * */
        List<Map<String,Object>> getAllUserInMap();
    
    • 1
    • 2
    • 3
    • 4
        <!--Map<String,Object> getAllUserInMap();-->
        <select id="getAllUserInMap" resultType="map">
            select * from t_user;
        </select>
    
    • 1
    • 2
    • 3
    • 4

    使用@Mapkey注解进行标识,在mapper接口的方法上添加@Mapkey注解,此时就可以将每条数据转换的map集合作为值,以某个字段的值作为键,放在同一个map集合中

        /*
        * 查询所有用户信息为map集合,一个表中会有多条数据,一个map集合对应一条数据,因此还需将所有map集合放在list集合中
        * */
    //    List<Map<String,Object>> getAllUserInMap();
        @MapKey("id")
        Map<String,Object> getAllUserInMap();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    Windoes命令CMD&powershell操作
    Blackfly S USB3工业相机:缓冲区处理
    深度学习 anaconda 安装问题
    STL的常用遍历算法(20221128)
    DataCon【签到题】挖矿流量检测
    【面试系列】Ruby 高频面试题
    软考 网络工程师如何复习?
    使用 Keras 和 TensorFlow Lite 的设备端大型语言模型
    docker安装redis
    Clion 中文输入的问题
  • 原文地址:https://blog.csdn.net/lyy_sss/article/details/125608290