본문으로 건너뛰기
Skillpedia
일반 코딩280k · #214

mybatis-patterns

하는 일

이 도구는 MyBatis 기술을 사용해 데이터베이스와 상호작용하는 코드를 정리하고 최적화하도록 돕습니다. 쿼리가 안전하고, 효율적이며, 이해하기 쉽도록 보장합니다.

사용하는 경우

  • ✓프로그램이 데이터에 접근하는 방식을 작성하거나 검토할 때.
  • ✓데이터베이스 명령을 작성하는 여러 방법 중에서 선택해야 할 때.
  • ✓프로그램이 데이터를 더 빨리 가져오도록 하고 싶을 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/mybatis-patterns/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/mybatis-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“MyBatis 데이터베이스 쿼리가 공격으로부터 안전하도록 어떻게 보장할 수 있을까요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 도구는 MyBatis 코드를 분석해 흔한 패턴을 찾고 개선 방법을 제안합니다. 데이터를 주고받는 방식과 트랜잭션을 관리하는 방식도 확인합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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 resultMap mappings, 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 @Mapper on each interface or with @MapperScan for a package. Do not mix registration approaches casually.
  • Keep the XML namespace equal 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 resultType for a simple one-to-one mapping whose column labels already match the target properties.
  • Use resultMap when aliases, type handlers, nested objects, or collections need explicit mapping.

…

자주 묻는 질문

MyBatis란 무엇인가요?

Java 프로그램이 데이터베이스와 통신하도록 돕는 도구입니다. SQL 명령을 더 체계적인 방식으로 작성할 수 있게 해 줍니다.

‘매퍼(mappers)’란 무엇인가요?

프로그램 코드와 SQL 명령 사이의 번역가와 같습니다. 어떤 데이터를 가져오고 어떻게 보여 줄지 정의합니다.

쿼리 보안이 왜 중요한가요?

안전하지 않은 쿼리는 악의적인 사용자가 데이터를 보거나 수정하도록 허용할 수 있습니다. 이 도구는 그런 일을 막는 데 도움이 됩니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
280k
순위
#214
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬