当前位置: 代码网 > it编程>编程语言>Java > MyBatis 注解Annotation实现CRUD操作全解析

MyBatis 注解Annotation实现CRUD操作全解析

2026年01月23日 Java 我要评论
mybatis 提供了 注解(annotation) 方式来实现 crud 操作,适用于简单、轻量级的数据库交互场景。相比 xml 配置,注解方式将 sql 直接写在 mapper 接口方法上,代码更

mybatis 提供了 注解(annotation) 方式来实现 crud 操作,适用于简单、轻量级的数据库交互场景。相比 xml 配置,注解方式将 sql 直接写在 mapper 接口方法上,代码更紧凑,开发效率更高。

一、mybatis 注解 crud 核心注解

注解作用说明
@select查询对应 select 语句
@insert插入对应 insert 语句
@update更新对应 update 语句
@delete删除对应 delete 语句
@param参数绑定多参数时指定参数名
@options配置选项如主键回填、缓存等
@results / @result结果映射替代 <resultmap>
@selectprovider 等动态 sql(高级)通过类方法生成 sql(较少用)

⚠️ 注意:mybatis 注解 不支持 <if><foreach> 等动态标签,复杂逻辑仍需 xml。

二、准备工作

1. 实体类(user.java)

public class user {
    private long id;
    private string name;
    private string email;
    // 构造函数、getter/setter 略
}

2. 数据库表(mysql 示例)

create table users (
    id bigint auto_increment primary key,
    name varchar(50) not null,
    email varchar(100)
);

三、注解实现 crud 完整示例

mapper 接口:usermapper.java

import org.apache.ibatis.annotations.*;
import java.util.list;
public interface usermapper {
    // 1. 新增(insert)
    @insert("insert into users(name, email) values(#{name}, #{email})")
    @options(usegeneratedkeys = true, keyproperty = "id", keycolumn = "id")
    int insert(user user);
    // 2. 根据 id 查询(select)
    @select("select * from users where id = #{id}")
    user selectbyid(@param("id") long id);
    // 3. 查询所有
    @select("select * from users")
    list<user> selectall();
    // 4. 更新(update)
    @update("update users set name = #{name}, email = #{email} where id = #{id}")
    int update(user user);
    // 5. 删除(delete)
    @delete("delete from users where id = #{id}")
    int deletebyid(@param("id") long id);
    // 6. 带条件查询(多参数)
    @select("select * from users where name like concat('%', #{name}, '%') and email = #{email}")
    list<user> findbynameandemail(@param("name") string name, @param("email") string email);
}

四、关键细节详解

1. 主键自增回填(@options)

@options(usegeneratedkeys = true, keyproperty = "id", keycolumn = "id")
  • usegeneratedkeys = true:启用 jdbc 获取自增主键;
  • keyproperty = "id":将生成的主键值赋给 user 对象的 id 字段;
  • keycolumn = "id":数据库主键列名(通常可省略,mybatis 自动推断)。

✅ 插入后,user.getid() 即可获得数据库生成的 id。

2. 多参数传递(@param)

当方法有多个参数时,必须使用 @param 指定名称:

@select("select * from users where name = #{name} and email = #{email}")
user findbytwoparams(@param("name") string name, @param("email") string email);

否则 mybatis 无法识别 #{name} 对应哪个参数。

3. 字段映射(@results)

如果数据库字段与 java 属性名不一致(如 user_name vs username),可用 @results 显式映射:

@select("select user_id, user_name, user_email from users where user_id = #{id}")
@results({
    @result(property = "id", column = "user_id"),
    @result(property = "name", column = "user_name"),
    @result(property = "email", column = "user_email")
})
user selectbyidwithmapping(@param("id") long id);

💡 若开启 mapunderscoretocamelcase,则无需手动映射。

五、测试示例(junit + mybatis)

@test
public void testcrud() throws ioexception {
    try (sqlsession session = sqlsessionfactory.opensession()) {
        usermapper mapper = session.getmapper(usermapper.class);
        // 插入
        user user = new user();
        user.setname("王五");
        user.setemail("wangwu@example.com");
        mapper.insert(user); // 此时 user.id 已被填充
        system.out.println("插入id: " + user.getid());
        // 查询
        user found = mapper.selectbyid(user.getid());
        system.out.println("查询结果: " + found.getname());
        // 更新
        found.setemail("new_wangwu@example.com");
        mapper.update(found);
        // 删除
        mapper.deletebyid(found.getid());
        session.commit(); // 注意:dml 操作需提交事务
    }
}

⚠️ 重要:mybatis 默认不自动提交事务!执行 insert/update/delete 后需调用 session.commit(),或配置 autocommit=true(不推荐生产环境使用)。

六、优点与局限性

✅ 优点

  • 代码简洁:sql 与接口方法紧耦合,无需额外 xml 文件;
  • 开发快速:适合单表、静态 sql 场景;
  • 易于理解:crud 逻辑一目了然。

❌ 局限性

问题说明
不支持动态 sql无法使用 <if><choose><foreach> 等标签
sql 复杂度受限多表 join、嵌套查询难以维护
无法复用 sql 片段不能像 xml 那样用 <sql> 提取公共部分
可读性差(长 sql)sql 写在字符串中,无语法高亮,易出错
调试困难sql 错误只能运行时发现,ide 无法校验

七、尽管注解方便,但在以下场景中,xml 映射文件是不可替代的:

1.动态 sql 支持强大

mybatis 的核心优势之一是 动态 sql(如 <if><choose><foreach> 等),而注解中写动态 sql 极其困难甚至不可读。

❌ 注解写动态 sql(不推荐):

@select("<script>" +
        "select * from users where 1=1 " +
        "<if test='name != null'> and name like concat('%', #{name}, '%') </if>" +
        "<if test='email != null'> and email = #{email} </if>" +
        "</script>")
list<user> findusers(@param("name") string name, @param("email") string email);
  • 字符串拼接易出错;
  • 无法格式化,难以维护;
  • 不支持 ide 语法高亮和校验。

✅ xml 写法(清晰优雅):

<select id="findusers" resulttype="user">
    select * from users
    <where>
        <if test="name != null">
            and name like concat('%', #{name}, '%')
        </if>
        <if test="email != null">
            and email = #{email}
        </if>
    </where>
</select>

📌 结论:只要涉及条件组合、分页、批量操作等,xml 是唯一合理选择。

2.复杂结果映射(resultmap)

当实体类与数据库字段命名不一致,或存在一对一/一对多关联查询时,需使用 <resultmap>

示例:用户 + 角色关联

<resultmap id="userwithroles" type="user">
    <id property="id" column="user_id"/>
    <result property="name" column="user_name"/>
    <collection property="roles" oftype="role">
        <id property="id" column="role_id"/>
        <result property="name" column="role_name"/>
    </collection>
</resultmap>
<select id="selectuserwithroles" resultmap="userwithroles">
    select u.id as user_id, u.name as user_name,
           r.id as role_id, r.name as role_name
    from users u
    left join user_roles ur on u.id = ur.user_id
    left join roles r on ur.role_id = r.id
    where u.id = #{id}
</select>

❌ 注解无法优雅表达这种嵌套映射,只能通过 @results 手动配置,代码冗长且不支持集合映射。

3.sql 复用与模块化

xml 支持 <sql> 片段复用:

<sql id="usercolumns">id, name, email</sql>
<select id="selectall" resulttype="user">
    select <include refid="usercolumns"/> from users
</select>

注解无法实现 sql 片段提取,导致重复代码。

4.可维护性与团队协作

  • xml 文件可被 dba 审查、优化;
  • sql 与 java 代码分离,符合“关注点分离”原则;
  • 更容易做 sql 性能调优、日志追踪;
  • 支持 mybatis generator 自动生成 xml 和实体类。

5.特殊 sql 语法兼容性更好

某些数据库特有语法(如 oracle 的 merge、postgresql 的 json 操作)在 xml 中更易书写和调试。

八、总结

功能注解实现是否推荐
单表 insert/update/delete✅ 支持✅ 简单场景推荐
单条件 select✅ 支持
多条件动态查询❌ 不支持(需拼字符串)❌ 不推荐
关联查询(join)⚠️ 可写但难维护❌ 不推荐
主键回填✅ 支持(@options)
字段映射✅ 支持(@results)⚠️ 开启驼峰更佳

🔔 结论
mybatis 注解是 轻量级 crud 的利器,但 不是万能方案
在快速开发、脚本工具、微服务 dao 层等场景下非常高效;
但在企业级应用中,xml 仍是主力,注解仅作补充。

注解是“糖”,xml 是“饭”
糖可以提味,但不能当饭吃。在真实业务系统中,xml 的灵活性、可读性和功能完整性使其具有不可替代的地位。

到此这篇关于mybatis 注解annotation实现crud操作全解析的文章就介绍到这了,更多相关mybatis 注解实现crud内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com