• MyBatis的各种查询功能


    查询一个实体类对象

    1. /**
    2. * 根据用户id查询用户信息
    3. * @param id
    4. * @return
    5. */
    6. User getUserById(@Param("id") int id);
    1. <select id="getUserById" resultType="User">
    2. select * from t_user where id = #{id}
    3. select>

    查询一个list集合 

    1. /**
    2. * 查询所有用户信息
    3. * @return
    4. */
    5. List getUserList();
    1. <select id="getUserList" resultType="User">
    2. select * from t_user
    3. select>

    当查询的数据为多条时,不能使用实体类作为返回值,否则会抛出异常

    TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值

     查询单个数据

    1. /**
    2. * 查询用户的总记录数
    3. * @return
    4. * 在MyBatis中,对于Java中常用的类型都设置了类型别名
    5. * 例如: java.lang.Integer-->int|integer
    6. * 例如: int-->_int|_integer
    7. * 例如: Map-->map,List-->list
    8. */
    9. int getCount();
    1. <select id="getCount" resultType="_integer">
    2. select count(id) from t_user
    3. select>

    查询一条数据为map集合 

    1. /**
    2. * 根据用户id查询用户信息为map集合
    3. * @param id
    4. * @return
    5. */
    6. Map getUserToMap(@Param("id") int id);
    1. <select id="getUserToMap" resultType="map">
    2. select * from t_user where id = #{id}
    3. select>

    查询多条数据为map集合 

    方式1 

    1. /**                                                                            
    2. * 查询所有用户信息为map集合                                                        
    3.      
    4. * @return                                                                    
    5. * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此
    6. 时可以将这些map放在一个list集合中获取
    7. */
    8. List> getAllUserToMap();

    方式2 

    1. /**                                                                            
    2. * 查询所有用户信息为map集合                                                        
    3.        
    4. * @return                                                                    
    5. * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并
    6. 且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的
    7. map集合
    8. */
    9. @MapKey("id")
    10. Map getAllUserToMap();
    1. <select id="getAllUserToMap" resultType="map">
    2. select * from t_user
    3. select>
  • 相关阅读:
    spring ioc
    ceph存储系统
    实战指南,SpringBoot + Mybatis 如何对接多数据源
    Codeforces补题
    Egg.js初步使用
    《乔布斯传》英文原著重点词汇笔记(九)【 chapter seven】
    Semantic Kernel 入门系列:🛸LLM降临的时代
    neo4j图数据库基本概念
    Synchronized锁的升级
    MATLAB环境下基于频率滑动广义互相关的信号时延估计方法
  • 原文地址:https://blog.csdn.net/m0_62436868/article/details/127781796