MyBatis-resultType

本文详细介绍了在MyBatis中,如何使用resultType来处理查询结果,包括查询单条记录返回对象、多条记录返回List以及返回Map的情况,同时提供了XML配置和注解配置的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要

  本文针对XML配置和注解配置说明resultType用法

正文

  下面的例子都用过查询User类实现

查询单条记录返回对象

  • XML配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.UserMapper">
    <!--resultType直接写对象的全类名 -->
    <select id="findById" resultType="com.example.User">
        select * from user where id=#{id}
    </select>
</mapper>
  • 注解配置
public interface UserMapper{
    @Select("select * from user where id=#{id}")
    User findById(Long id);
}

查询多条记录返回List

  • XML配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.UserMapper">
    <!--resultType直接写对象的全类名 -->
    <select id="findList" resultType="com.example.User">
        select * from user
    </select>
</mapper>
  • 注解配置
public interface UserMapper{
    @Select("select * from user")
    List<User> findList();
}

查询单条记录返回Map

  在没有查询结果没有实体类的情况,我会使用这种方式。

  • XML配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.UserMapper">
    <!--resultType直接写对象的全类名 -->
    <select id="findById" resultType="map">
        select * from user where id=#{id}
    </select>
</mapper>
  • 注解配置
public interface UserMapper{
    @Select("select * from user where id=#{id}")
    Map<String,Object> findById(Long id);
}

查询多条记录返回Map

  对部分列需要处理时,我会使用这种方式

  • XML配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.UserMapper">
    <!--resultType直接写对象的全类名 -->
    <select id="findMap" resultType="com.example.User">
        select * from user
    </select>
</mapper>

public interface UserMapper{
    // 通过@MapKey注解指定作为key的列名
    @MapKey("id")
    Map<Long,User> findMap();
}
  • 注解配置
public interface UserMapper{
    @MapKey("id")
    @Select("select * from user")
    Map<Long,User> findMap();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值