全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-20 8 分钟 ✍️ juanwangdev

select 查询语句

select 是最常用的 SQL 语句类型,下面梳理其核心用法与配置。

基础查询语法

XML
<select id="selectById" resultType="com.example.entity.User">
    SELECT id, username, email FROM user WHERE id = #{id}
</select>
属性说明
id方法名,必须与 Mapper 接口方法名一致
parameterType参数类型,可省略(MyBatis 自动推断)
resultType返回值类型,与 resultMap 二选一
resultMap引用外部 resultMap,处理复杂映射

resultType 与 resultMap 区别

XML
<!-- resultType 简单类型 -->
<select id="countAll" resultType="int">
    SELECT COUNT(*) FROM user
</select>

<!-- resultMap 复杂映射 -->
<select id="selectWithRole" resultMap="UserWithRoleMap">
    SELECT u.*, r.role_name 
    FROM user u LEFT JOIN role r ON u.role_id = r.id
</select>

<resultMap id="UserWithRoleMap" type="com.example.entity.User">
    <id column="id" property="id"/>
    <result column="username" property="username"/>
    <association property="role" javaType="com.example.entity.Role">
        <result column="role_name" property="roleName"/>
    </association>
</resultMap>

注意:resultType 与 resultMap 不能同时使用。

参数传递

XML
<!-- 单参数 -->
<select id="selectById" resultType="com.example.entity.User">
    SELECT * FROM user WHERE id = #{id}
</select>

<!-- 多参数使用 @Param -->
<select id="selectByNameAndEmail" resultType="com.example.entity.User">
    SELECT * FROM user 
    WHERE username = #{name} AND email = #{email}
</select>

模糊查询

XML
<!-- 方式一:bind 标签 -->
<select id="selectByNameLike" resultType="com.example.entity.User">
    <bind name="pattern" value="'%' + name + '%'"/>
    SELECT * FROM user WHERE username LIKE #{pattern}
</select>

<!-- 方式二:CONCAT 函数 -->
<select id="selectByNameLike" resultType="com.example.entity.User">
    SELECT * FROM user WHERE username LIKE CONCAT('%', #{name}, '%')
</select>

要点总结

  • select 是最常用的 SQL 语句类型
  • resultType 与 resultMap 二选一,不可同时使用
  • 单参数可省略 parameterType,多参数推荐 @Param 注解
  • 模糊查询推荐 bind 标签或 CONCAT 函数

📝 发现内容有误?点击此处直接编辑

← 上一篇 mapper 根元素
下一篇 → update 更新语句
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库