1. Spring 어노테이션 개념 정리
@Autowired | 의존성 주입 (Dependency Injection) 수행 |
@Controller | Spring MVC 컨트롤러를 정의 |
@Service | 비즈니스 로직을 처리하는 서비스 계층을 정의 |
@Repository | 데이터 액세스 계층을 정의 |
@RestController | @Controller + @ResponseBody (REST API 컨트롤러) |
@Configuration | Spring 설정 클래스 지정 |
@Component | Spring에서 관리해야 하는 일반적인 클래스 지정 |
@Configuration vs @Component 차이
- @Configuration: 스프링 빈을 설정하고 등록하는 클래스에 사용됨 (주로 @Bean과 함께 사용).
- @Component: 단순히 스프링이 관리해야 하는 일반 클래스를 등록하는 데 사용됨.
💡 POJO (Plain Old Java Object)란?
특정 프레임워크에 종속되지 않는 순수한 Java 클래스를 의미하며, 일반적으로 @Component와 함께 사용하여 스프링 빈으로 등록 가능.
2. MyBatis 설정 (DB 접근 기술)
✅ MyBatis 개념 이해
✅ MyBatis 의존성 설정
✅ application.yml 설정
✅ Mapper 인터페이스 및 XML 매퍼 파일 생성
📌 MyBatis 란?
MyBatis는 SQL 쿼리를 직접 작성하면서도, 객체와 SQL을 매핑하는 기능을 제공하는 데이터베이스 연동 프레임워크.
✅ 순수 JDBC 코드와의 차이점
💡 JDBC 코드 예제
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name"));
}
🚀 MyBatis 사용시
- SQL과 Java 코드를 분리할 수 있음
- XML 또는 어노테이션을 활용한 매핑 가능
- 반복되는 JDBC 코드 제거
3. MyBatis 설정 추가
1) MyBatis 의존성 추가 (build.gradle)
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.3'
- mybatis-spring-boot-starter → MyBatis를 Spring Boot에서 쉽게 사용할 수 있도록 도와주는 라이브러리.
- Spring Boot 프로젝트에서 JDBC 작업을 할 때 MyBatis와 함께 사용.
2) application.yml 설정
mybatis:
mapper-locations:
- classpath:mapper/**/*.xml # MyBatis 매퍼 파일 위치
configuration:
map-underscore-to-camel-case: true # 언더스코어 네이밍을 카멜 케이스로 변환
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # SQL 로그 출력
- mapper-locations → **SQL 매퍼 파일(XML)**의 위치를 지정.
- map-underscore-to-camel-case: true → user_id → userId 자동 변환.
- log-impl: org.apache.ibatis.logging.stdout.StdOutImpl → SQL 실행 로그를 콘솔에서 확인 가능.
4. MyBatis Mapper 생성
패키지 구조 확인
📂 src/main/java/com/tenco/bank/repository/interfaces
├── AccountRepository.java
├── UserRepository.java
📂 src/main/resources/mapper
├── account.xml
├── user.xml
1) UserRepository.java 생성
package com.tenco.bank.repository.interfaces;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.tenco.bank.repository.model.User;
@Mapper
public interface UserRepository {
public int insert(User user);
public int updateById(User user);
public int deleteById(Integer id);
public User findById(Integer id);
public List<User> findAll();
}
- @Mapper → MyBatis와 연결되는 인터페이스임을 선언.
- 메서드 선언 → MyBatis XML에서 해당 메서드와 매핑되는 SQL을 실행함.
2) user.xml (SQL 쿼리 정의)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tenco.bank.repository.interfaces.UserRepository">
<insert id="insert">
insert into user_tb (username, password, fullname, created_at)
values (#{username}, #{password}, #{fullname}, now())
</insert>
<update id="updateById">
update user_tb set username = #{username},
password = #{password},
fullname = #{fullname}
where id = #{id}
</update>
<delete id="deleteById">
delete from user_tb where id = #{id}
</delete>
<select id="findById" resultType="com.tenco.bank.repository.model.User">
select * from user_tb where id = #{id}
</select>
<select id="findAll" resultType="com.tenco.bank.repository.model.User">
select * from user_tb
</select>
</mapper>
- <insert> → 새 사용자 추가.
- <update> → 특정 사용자의 정보를 업데이트.
- <delete> → 사용자 삭제.
- <select> → 사용자를 ID로 검색 / 모든 사용자 검색.
3) AccountRepository.java 생성
package com.tenco.bank.repository.interfaces;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.tenco.bank.repository.model.Account;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface AccountRepository {
public int insert(Account account);
public int updateById(Account account);
public int deleteById(@Param("id") Integer id);
public List<Account> findByUserId(@Param("userId") Integer userId);
public Account findByNumber(@Param("number") String number);
}
4) account.xml (SQL 쿼리 정의)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tenco.bank.repository.interfaces.AccountRepository">
<insert id="insert">
insert into account_tb (number, password, balance, user_id, created_at)
values (#{number}, #{password}, #{balance}, #{userId}, now())
</insert>
<update id="updateById">
update account_tb set number = #{number},
password = #{password},
balance = #{balance},
user_id = #{userId}
where id = #{id}
</update>
<delete id="deleteById">
delete from account_tb where id = #{id}
</delete>
<select id="findByUserId" resultType="com.tenco.bank.repository.model.Account">
select * from account_tb where user_id = #{userId}
</select>
<select id="findByNumber" resultType="com.tenco.bank.repository.model.Account">
select * from account_tb where number = #{number}
</select>
</mapper>
5. MyBatis를 활용한 데이터 조회 테스트
@Autowired
private UserRepository userRepository;
public void testMyBatis() {
User user = userRepository.findById(1);
System.out.println("사용자 이름: " + user.getUsername());
}
- Spring의 주요 어노테이션 개념 정리
- MyBatis 설정 (application.yml 포함)
- Mapper 인터페이스 및 XML 파일 작성
- 데이터 조회 테스트 완료