Spring Boot 프로젝트에 Generic Mapper 통합 방법

기존에는 mapper.xml 파일을 통해 직접 SQL을 작성해야 했지만, 일반적인 쿼리 작업을 위해 Generic Mapper를 도입한 이후로는 더 이상 복잡한 XML 설정 없이도 효율적으로 데이터베이스 작업이 가능해졌습니다. 이 라이브러리는 자주 사용되는 기본 쿼리(예: selectOne, insert, update, delete)를 미리 구현해두었기 때문에 개발 속도가 크게 향상됩니다.

실제 프로젝트에서는 mapper.xml과 유니버설 매퍼를 혼용하여 사용할 수 있으며, 상황에 따라 적절히 선택하면 됩니다. 이번 글에서는 간단한 예제를 통해 Spring Boot + Generic Mapper의 통합 과정을 단계별로 설명합니다.

1. 프로젝트 생성 및 의존성 설정

  • Spring Boot 초기화 시 다음 종속성을 포함합니다 (Lombok은 필수 아님).
  • mvnrepository.com에서 필요한 라이브러리 추가:
<!-- Alibaba Druid 데이터베이스 연결 풀 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.21</version>
</dependency>

<!-- Generic Mapper 스타터 -->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

2. 공통 매퍼 인터페이스 정의

commons 패키지 아래에 기본 매퍼 인터페이스를 생성합니다.

@Component
public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

3. application.properties 구성

데이터베이스 연결 정보와 관련 설정을 포함합니다.

server:
  port: 8082

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/your_db?useSSL=false&serverTimezone=UTC
    username: root
    password: your_password
    type: com.alibaba.druid.pool.DruidDataSource

mybatis:
  type-aliases-package: org.woodside.demo.entity
  configuration:
    map-underscore-to-camel-case: true

mapper:
  identity: MYSQL
  mappers: org.woodside.demo.commons.BaseMapper
  not-empty: true
  enum-as-simple-type: true

4. 계층 구조 및 클래스 작성

다음과 같은 디렉토리 구조를 따릅니다:

  • controller: 요청 처리
  • service: 비즈니스 로직 추상화
  • service.impl: 서비스 구현
  • mapper: 데이터 접근 계층

Controller 예시

@RestController
public class CouponController {

    @Autowired
    private CouponService couponService;

    @GetMapping("/list")
    public List<Coupon> getAll() {
        return couponService.findAll();
    }
}

Service 인터페이스

public interface CouponService {
    List<Coupon> findAll();
}

Service 구현체

@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Override
    public List<Coupon> findAll() {
        return couponMapper.selectAll();
    }
}

Mapper 인터페이스

@Mapper
@Component
public interface CouponMapper extends BaseMapper<Coupon> {
}

주의사항: 커스텀 BaseMapper를 상속받아야만 일반 매퍼의 기능을 활용할 수 있습니다.

5. 실행 및 검증

프로젝트를 실행하고 GET /list 엔드포인트에 접근하면, 데이터베이스의 모든 레코드가 성공적으로 반환됩니다. 이로써 Spring Boot + Generic Mapper의 통합이 완료되었습니다.

결과적으로, 복잡한 mapper.xml 파일 관리 없이도 쉽게 CRUD 작업이 가능하며, 코드 구조도 깔끔해집니다.

태그: Spring Boot Generic Mapper MyBatis Druid jpa

8월 3일 07:35에 게시됨