mybatis-patterns
Qué hace
Esta herramienta ayuda a organizar y optimizar el código que interactúa con bases de datos mediante la tecnología MyBatis. Asegura que tus consultas sean seguras, eficientes y fáciles de entender.
Cuándo usarla
- ✓Al escribir o revisar cómo el programa accede a los datos.
- ✓Al decidir entre distintas formas de escribir los comandos de base de datos.
- ✓Cuando quieres que el programa obtenga los datos más rápido.
Link de la skill
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/mybatis-patterns/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“¿Cómo puedo asegurar que mis consultas de base de datos en MyBatis estén protegidas contra ataques?”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
Analiza tu código de MyBatis para encontrar patrones habituales y sugerir mejoras. Revisa cómo se envían y reciben los datos y cómo se gestionan las transacciones.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
MyBatis Patterns
Use MyBatis when SQL control and explicit mappings matter. Keep SQL readable,
make mapper contracts small, and put business transactions in the service layer.
Pair this skill with springboot-patterns for application structure,
database-migrations for schema changes, postgres-patterns or
mysql-patterns for engine-specific SQL, and security-review for untrusted
input and access-control concerns.
When to Activate
- Adding or reviewing MyBatis mapper interfaces or XML files
- Choosing between XML mappers, annotation mappers, and generated SQL
- Designing
resultMapmappings, joins, nested collections, or projections - Reviewing dynamic SQL, parameter binding, pagination, or batch writes
- Debugging N+1 queries, slow statements, connection use, or transaction bugs
- Integrating MyBatis-Spring into Spring Boot or an XML-first legacy application
How It Works
Use a thin mapper for persistence operations and keep business rules in a service. A typical flow is:
Controller / batch job -> Service (@Transactional) -> Mapper -> Database
- Register mappers once, either with
@Mapperon each interface or with@MapperScanfor a package. Do not mix registration approaches casually. - Keep the XML
namespaceequal to the mapper interface's fully qualified name. - Give each statement a stable, descriptive
id; treat mapper methods as a persistence API that can be tested independently. - Return a domain DTO or projection for read paths instead of exposing a large mutable map when the shape is known.
- Keep schema changes in migrations. Do not make mapper startup silently create or alter production tables.
Examples
@MapperScan("com.example.user.persistence")
@Configuration
class MyBatisConfig {
}
public interface UserMapper {
UserSummary findSummaryById(long userId);
}
<mapper namespace="com.example.user.persistence.UserMapper">
<select id="findSummaryById"
parameterType="long"
resultType="com.example.user.persistence.UserSummary">
SELECT id, display_name AS displayName, status
FROM users
WHERE id = #{userId}
</select>
</mapper>
Parameter Binding and SQL Safety
Use #{...} for values. MyBatis binds it as a prepared-statement parameter.
Treat ${...} as raw SQL text: it is only appropriate for a value selected
from a closed, application-owned allowlist such as a sort-column map.
private static final Map<String, String> SORT_COLUMNS = createSortColumns();
private static Map<String, String> createSortColumns() {
Map<String, String> columns = new HashMap<>();
columns.put("name", "display_name");
columns.put("created", "created_at");
return Collections.unmodifiableMap(columns);
}
String sortColumn = SORT_COLUMNS.getOrDefault(request.sort(), "created_at");
String sortDirection = request.descending() ? "DESC" : "ASC";
// The mapper receives only an allowlisted identifier; user input is never
// passed directly to ${sortColumn} or ${sortDirection}.
<select id="findPage" resultType="com.example.user.persistence.UserSummary">
SELECT id AS id,
display_name AS displayName,
status AS status,
created_at AS createdAt
FROM users
WHERE tenant_id = #{tenantId}
ORDER BY ${sortColumn} ${sortDirection}
LIMIT #{limit}
</select>
Derive tenantId from the authenticated principal or a server-side tenant
context, never from a request field. Authenticate the principal and verify
that it is authorized for the tenant before invoking the mapper; keep the
tenant_id predicate in SQL as defense in depth.
If possible, avoid ${} entirely by selecting among fixed statements or by
using a database-specific query builder. Never interpolate user input into a
table name, column name, ORDER BY, WHERE fragment, or SQL expression.
For multiple parameters, use a request object or explicit @Param names:
List<UserSummary> findActive(
@Param("tenantId") long tenantId,
@Param("statuses") Set<UserStatus> statuses
);
Do not use the deprecated external parameterMap element. Prefer inline
parameter mappings and explicit jdbcType for nullable values when the JDBC
driver needs it.
XML, Result Types, and Result Maps
- Use
resultTypefor a simple one-to-one mapping whose column labels already match the target properties. - Use
resultMapwhen aliases, type handlers, nested objects, or collections need explicit mapping.
…
Preguntas frecuentes
¿Qué es MyBatis?
MyBatis es una herramienta que ayuda a los programas en Java a comunicarse con bases de datos, permitiendo escribir comandos SQL de forma más organizada.
¿Qué son los 'mappers'?
Los mappers son como traductores entre el código de tu programa y los comandos SQL. Definen qué datos se obtienen y cómo se presentan.
¿Por qué es importante la seguridad de las consultas?
Las consultas inseguras pueden permitir que personas malintencionadas accedan o modifiquen tus datos. Esta herramienta ayuda a evitarlo.
Detalles
Descripción original del autor
MyBatis and MyBatis-Spring patterns for mapper design, XML and annotation SQL, result mapping, dynamic SQL safety, transactions, batching, pagination, and query performance. Use when building or reviewing Java persistence code with MyBatis, Spring Boot, MyBatis-Spring, or MyBatis-based legacy applications.
repo: affaan-m/ECC
Popularidad
- Estrellas en GitHub
- 280 mil
- Posición en el ranking
- #214
- Licencia
- MIT
- Actualizada
- 15/10/2026
Comentarios
- …
Más skills de este repositorio
accessibility
280 milAyuda a tu agente a crear interfaces accesibles para todos. Asegura que webs y apps funcionen bien para personas con discapacidad, como ciegas o con movilidad reducida.
agent-architecture-audit
280 milHace que tu agente compruebe que todo funciona bien. Encuentra y corrige problemas en sistemas de IA para que se comporten como se espera.
agent-eval
280 milAyuda a tu agente a comparar distintas herramientas de programación con IA. Mide cuál es más rápida, más barata y más fiable para tareas concretas.
agent-harness-construction
280 milHace que tu agente entienda mejor cómo realizar tareas. Optimiza las herramientas e instrucciones que usa para aumentar sus probabilidades de éxito.
Skills parecidas
diffs
394 milPermite que tu agente genere un diff real y compartible de los cambios, como enlace de visualización o archivo de imagen, en lugar de un resumen escrito a mano.
coding-agent
394 milAyuda a tu agente a pasar un trabajo de programación grande a Codex, Claude Code u OpenCode como trabajador en segundo plano, y después revisar su progreso.
gh-issues
394 milAyuda a tu agente a encontrar incidencias de GitHub, elegir cuáles trabajar y abrir pull requests con correcciones, incluido el seguimiento de los comentarios de revisión.