MCPInstall

mybatis-patterns

MyBatis 核心 ORM 技能。覆盖 XML vs 注解 SQL选择、ResultMap复用(extends)、关联查询(association/collection join vs 嵌套select/N+1决策)、分页插件配置、和$的SQL注入防护、动态SQL(if/where/set/foreach/choose)最佳实践、columnPrefix解决同表多次JOIN。 当用户编写 MyBatis Mapper XML、处理关联查询、配置分页、防范SQL注入时使用。

Installs
109
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/full-stack-skills/java-skills --skill mybatis-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads mybatis-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

MyBatis 核心 ORM

来源:https://mybatis.org/mybatis-3/
GitHub:https://github.com/mybatis/mybatis-3

Capability Boundaries

✅ Strong Suits

  1. XML vs 注解选择 — 简单CRUD用注解,复杂查询/动态SQL用XML
  2. ResultMap复用 — extends继承、discriminator鉴别器、columnPrefix 同表多JOIN
  3. 关联查询 — association(一对一)/collection(一对多),Join查询(推荐) vs 嵌套select(N+1风险)
  4. 动态SQL — if/choose/when/otherwise/where/set/foreach/trim/return
  5. 防注入 — #{}预编译 vs ${}表名/列名(必须白名单校验)
  6. 分页 — RowBounds(不推荐) / PageHelper(推荐) 物理分页
  7. sql片段 + include — 公共SQL片段复用

❌ Out of Scope

  1. MyBatis-Plus LambdaWrapper → mybatis-plus-patterns
  2. Spring Data JPA → spring-data-jpa(已有技能)

LLM最常犯的错误

#错误正确做法
1简单CRUD也用XML写@Select("SELECT * FROM user WHERE id=#{id}") 注解即可
2N+1查询:循环查子表Join查询(推荐) 或 association/collection + batch select
3${column} 动态排序无白名单先检查 columnName 是否在白名单中,否则 SQL 注入
4不配置 resultMap 用别名映射定义 <resultMap> + <result column="user_name" property="userName"/>
5SELECT * 全部字段只查需要的字段(尤其大字段/TEXT/BLOB)
6模糊查询 LIKE '%${keyword}%' SQL注入LIKE CONCAT('%', #{keyword}, '%') 预编译
7多表 JOIN 不处理列名冲突用别名 + resultMap column 映射
8不同表 JOIN 同表两次,手动写所有列用 <association columnPrefix="addr_" 复用 resultMap

核心模式

模式 1: ResultMap 复用 + extends

<!-- 基础 ResultMap -->
<resultMap id="BaseResultMap" type="com.example.User">
    <id column="id" property="id"/>
    <result column="user_name" property="userName"/>
    <result column="email" property="email"/>
    <result column="status" property="status"/>
</resultMap>

<!-- 继承 + 关联(推荐 Join 方式) -->
<resultMap id="UserWithDept" extends="BaseResultMap" type="com.example.UserVO">
    <association property="dept" javaType="Department"
        resultMap="com.example.DeptMapper.BaseResultMap"
        columnPrefix="dept_"/>  <!-- ← 同名字段加前缀 -->
    <collection property="roles" ofType="Role"
        resultMap="com.example.RoleMapper.BaseResultMap"
        columnPrefix="role_"/>
</resultMap>

模式 2: Join 查询(推荐,替代嵌套 select)

<!-- ✅ 推荐:Join 查询 → 一次SQL,无N+1 -->
<select id="selectUserWithDept" resultMap="UserWithDept">
    SELECT u.id, u.user_name, u.email, u.status,
           d.id AS dept_id, d.dept_name AS dept_dept_name,  <!-- ← 加前缀 -->
           r.id AS role_id, r.role_name AS role_role_name
    FROM sys_user u
    LEFT JOIN sys_dept d ON u.dept_id = d.id
    LEFT JOIN sys_user_role ur ON u.id = ur.user_id
    LEFT JOIN sys_role r ON ur.role_id = r.id
    WHERE u.id = #{id}
</select>

<!-- ❌ 避免:嵌套 select 导致 N+1 -->
<resultMap id="UserWithDeptNested" extends="BaseResultMap" type="com.example.UserVO">
    <association property="dept" javaType="Department"
        column="dept_id" select="selectDeptById"/>  <!-- ← 每次查询一个部门 -->
</resultMap>
<!-- 如果查100个用户 → 1(主查询) + 100(部门查询) = 101次SQL -->

模式 3: 动态 SQL 完整模式

<select id="findByCondition" resultMap="BaseResultMap">
    SELECT id, user_name, email, status, create_time
    FROM sys_user
    <where>  <!-- ← 自动处理 AND/OR 前缀 -->
        <if test="username != null and username != ''">
            AND user_name LIKE CONCAT('%', #{username}, '%')  <!-- ✅ 防注入 -->
        </if>
        <if test="status != null">
            AND status = #{status}
        </if>
        <if test="deptId != null">
            AND dept_id = #{deptId}
        </if>
    </where>
    <if test="orderBy != null">
        ORDER BY ${orderBy}  <!-- ⚠️ 必须白名单校验 -->
    </if>
</select>

<!-- 批量插入 -->
<insert id="batchInsert">
    INSERT INTO sys_user (user_name, email, status)
    VALUES
    <foreach collection="list" item="user" separator=",">
        (#{user.userName}, #{user.email}, #{user.status})
    </foreach>
</insert>

<!-- 动态更新(set 自动去尾逗号) -->
<update id="updateSelective">
    UPDATE sys_user
    <set>
        <if test="userName != null">user_name = #{userName},</if>
        <if test="email != null">email = #{email},</if>
        <if test="status != null">status = #{status},</if>
    </set>
    WHERE id = #{id}
</update>

<!-- choose/when/otherwise 多分支 -->
<select id="findByCondition" resultMap="BaseResultMap">
    SELECT * FROM sys_user
    <where>
        <choose>
            <when test="queryType == 'name'">AND user_name LIKE CONCAT('%', #{keyword}, '%')</when>
            <when test="queryType == 'email'">AND email = #{keyword}</when>
            <otherwise>AND status = 'ACTIVE'</otherwise>
        </choose>
    </where>
</select>

模式 4: SQL 片段复用

<sql id="BaseColumns">
    id, user_name, email, status, create_time, update_time
</sql>

<select id="selectById" resultMap="BaseResultMap">
    SELECT <include refid="BaseColumns"/>
    FROM sys_user WHERE id = #{id}
</select>

模式 5: 注解方式(简单查询)

@Select("SELECT * FROM sys_user WHERE id = #{id}")
@Results(id = "userMap", value = {
    @Result(column = "user_name", property = "userName"),
    @Result(column = "dept_id", property = "deptId")
})
User findById(Long id);

模式 6: 排序字段白名单校验

// ✅ 安全:校验排序字段在白名单中
private static final Set<String> SORT_COLUMNS = Set.of(
    "create_time", "update_time", "user_name", "status"
);

public List<User> findByCondition(String orderBy, boolean asc) {
    if (!SORT_COLUMNS.contains(orderBy)) {
        throw new SecurityException("非法排序字段: " + orderBy);
    }
    // 传入 ${orderBy} 安全使用
}

Gotchas

  1. #{} 会加引号自动转义,${} 直接拼接 — 用户输入必须用 #{}
  2. ${} 用于动态表名/列名/排序时 — 必须白名单校验,否则 SQL 注入
  3. association 的 select 属性是延迟加载 — 每个关联触发一次查询 = N+1,用 Join 查询替代
  4. resultType 和 resultMap 不能同时使用 — 二选一
  5. Mapper 接口和 XML 必须在同一 package 路径 — 否则配置 mybatis.mapper-locations
  6. Spring Boot 默认开启驼峰映射 — mybatis.configuration.map-underscore-to-camel-case=true
  7. @Select/@Results 不定义 @ResultMap ID — 不能在 XML 中复用
  8. JOIN 查询中 resultMap columnPrefix — 解决同名字段的唯一方式,比写别名更简洁
  9. WHERE 1=1 不如 <where> — <where> 自动处理 AND/OR 前缀,更优雅
  10. <foreach> 注意 IN 列表为空 — 空列表导致 SQL 语法错误,提前判空
  11. PageHelper 分页的原理是 ThreadLocal — 分页后必须紧跟查询,中间不能有其他操作
  12. MyBatis 二级缓存慎用 — 跨 session 缓存导致数据不一致,分布式环境不要用

Data Privacy

本技能不收集、存储或传输任何用户数据。

FAQ

What does the mybatis-patterns skill do?

MyBatis 核心 ORM 技能。覆盖 XML vs 注解 SQL选择、ResultMap复用(extends)、关联查询(association/collection join vs 嵌套select/N+1决策)、分页插件配置、和$的SQL注入防护、动态SQL(if/where/set/foreach/choose)最佳实践、columnPrefix解决同表多次JOIN。 当用户编写 MyBatis Mapper XML、处理关联查询、配置分页、防范SQL注入时使用。

How do I install mybatis-patterns?

Run npx skills add https://github.com/full-stack-skills/java-skills --skill mybatis-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/mybatis-patterns/ (personal) or .claude/skills/mybatis-patterns/ (project).

Which AI agents can use mybatis-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is mybatis-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains mybatis-patterns?

It is published by full-stack-skills in full-stack-skills/java-skills. It has 109 recorded installs.

More from full-stack-skills/java-skills

View all →

java-development-manual

full-stack-skills/java-skills

Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。 当用户需要:(1) 编写或审查Java代码 (2) 检查命名/代码规范 (3) 处理异常和日志 (4) 编写单元测试 (5) 安全编码 (6) 数据库设计 (7) 工程架构设计时使用此skill。 触发词:Java规范、阿里规约、代码规范、开发手册、编程规约、异常处理、单元测试、安全、MySQL、工程结构、设计模式。

Backend & APIs119 installs

mybatis-plus-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs114 installs

java-code-comments

full-stack-skills/java-skills

Provides comprehensive guidance for adding Java code comments following industry standards and best practices. This skill helps add class-level comments, method-level comments, and field-level comments to Java code. Use when the user wants to add comments to Java code, needs to document Java classes/methods/fields, wants to improve code documentation, or needs to generate JavaDoc comments. This skill covers Controller, Service, ServiceImpl, Mapper, Model, Entity, BO (Business Object), DTO, VO, and other common Java component types. The skill follows a systematic workflow: scan codebase, identify components, create todo list, and add comments in order (class comments → method comments → field comments).

Backend & APIs112 installs

java-conventions

full-stack-skills/java-skills

统一 Java 项目编码规范与注释规范(SLF4J+Lombok 日志、Bean Lombok 注解选择、判空 Objects/Optional、工具类优先级 Spring→Apache Commons→Hutool→Guava、复杂逻辑用设计模式/简单逻辑不拆分、Controller/Service/ServiceImpl/Mapper 注释一致性)。当需要“按 Java 规范重构/Review/补全注释/统一日志/统一工具类使用/补全 JavaDoc”时使用。

Backend & APIs108 installs

redis-redisson-patterns

full-stack-skills/java-skills

Redis + Redisson 缓存与分布式锁技能。覆盖缓存Key命名规范、过期时间设置原则、RedisTemplate序列化选择(JSON vs JDK vs String)、Redisson分布式锁三大模式(watchDog/tryLock 有leaseTime/无leaseTime 决策)、缓存穿透(布隆/空值缓存)/击穿(互斥锁)/雪崩(随机TTL)防护、Caffeine vs Redis选择决策。 纠正 LLM:不设过期时间、StringRedisTemplate和RedisTemplate混用、Redisson锁不 try-finally unlock、看门狗在指定 leaseTime 时不生效。

Data & Databases100 installs

mapstruct-patterns

full-stack-skills/java-skills

MapStruct 最佳实践模式。从官方 Reference Guide 提炼,覆盖 Mapper 三种定义方式(接口/抽象类/default方法)、Spring 注入策略(CONSTRUCTOR推荐/SETTER解决循环依赖)、嵌套映射模式(显式子方法 dot notation 一次性配置)、@Qualifier @Named 的安全选择、Lombok 集成规则、@MappingComposition 谨慎使用。 纠正 LLM 最常见的错误:用反射 BeanUtils 而非编译期 MapStruct、嵌套映射全写在一个方法、不知 SETTER 解决循环依赖。

Backend & APIs97 installs

Popular data & databases skills

View category →

Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pgcron, pgmq), vector/semantic search (pgvector), and restoring dumps (pgrestore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.

OfficialData & Databases462.2K installs

prisma-client-api

prisma/skills

Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".

OfficialData & Databases393.5K installs

Deprecated compatibility name for prisma-orm-setup. Use only when a user or existing integration explicitly invokes prisma-database-setup; otherwise select prisma-orm-setup.

OfficialData & Databases392.3K installs

prisma-cli

prisma/skills

Prisma ORM 7 CLI reference for existing Prisma 7 applications or explicitly selected Prisma 7 workflows. Covers prisma init, generate, migrate, db, dev, studio, and mcp. For setup, connection repair, or Prisma 8, use prisma-orm-setup; not the Prisma Platform CLI.

OfficialData & Databases390.8K installs

prisma-postgres

prisma/skills

Deprecated compatibility name for prisma-postgres-setup. Use only when a user or existing integration explicitly invokes prisma-postgres; otherwise select prisma-postgres-setup.

OfficialData & Databases384.4K installs

Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.

OfficialData & Databases378.9K installs