반응형
오늘은 MyBatis에서 제공하는 동적 SQL 기능을 활용하여 다양한 조건을 기반으로 데이터를 조회하거나 수정하는 방법을 학습합니다. 동적 SQL은 쿼리를 유연하게 작성할 수 있게 해 주며, 조건문이나 반복문 같은 제어 구조를 SQL에 추가할 수 있습니다.
1. 동적 SQL이란?
MyBatis의 동적 SQL은 XML 매퍼에서 <if>, <choose>, <where>, <foreach> 등의 태그를 활용하여 동적으로 쿼리를 생성할 수 있도록 도와줍니다. 이는 주로 조건에 따라 다른 쿼리를 실행하거나 반복문으로 다수의 데이터를 처리할 때 유용합니다.
2. 환경 설정
동적 SQL을 사용하는 데 추가적인 설정은 필요하지 않으며, 기존 MyBatis 매퍼와 동일한 방식으로 활용할 수 있습니다.
3. 실습: 동적 조건으로 데이터 조회하기
(1) 매퍼 파일 작성
아래는 EmployeeMapper.xml 파일에서 동적 SQL을 사용하는 예제입니다.
<mapper namespace="com.example.mapper.EmployeeMapper">
<!-- 동적 조건에 따른 데이터 조회 -->
<select id="getEmployeesByDynamicCondition" resultType="com.example.domain.Employee">
SELECT * FROM employees
<where>
<if test="firstName != null">
AND first_name = #{firstName}
</if>
<if test="lastName != null">
AND last_name = #{lastName}
</if>
<if test="minSalary != null">
AND salary >= #{minSalary}
</if>
</where>
ORDER BY employee_id
</select>
</mapper>
(2) 데이터 객체와 파라미터 작성
EmployeeSearchCriteria 클래스를 생성하여 검색 조건을 담는 객체를 정의합니다.
package com.example.domain;
public class EmployeeSearchCriteria {
private String firstName;
private String lastName;
private Double minSalary;
// Getters and Setters
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Double getMinSalary() {
return minSalary;
}
public void setMinSalary(Double minSalary) {
this.minSalary = minSalary;
}
}
(3) Mapper 인터페이스 작성
EmployeeMapper.java 인터페이스에 메서드를 정의합니다.
package com.example.mapper;
import com.example.domain.Employee;
import com.example.domain.EmployeeSearchCriteria;
import java.util.List;
public interface EmployeeMapper {
List<Employee> getEmployeesByDynamicCondition(EmployeeSearchCriteria criteria);
}
(4) 서비스 로직 작성
EmployeeService에서 검색 조건을 적용한 로직을 구현합니다.
package com.example.service;
import com.example.domain.Employee;
import com.example.domain.EmployeeSearchCriteria;
import com.example.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
public List<Employee> getEmployeesByDynamicCondition(EmployeeSearchCriteria criteria) {
return employeeMapper.getEmployeesByDynamicCondition(criteria);
}
}
(5) 테스트 코드 작성
검색 조건을 달리하여 동적 SQL이 제대로 동작하는지 확인합니다.
package com.example;
import com.example.domain.Employee;
import com.example.domain.EmployeeSearchCriteria;
import com.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class TestRunner implements CommandLineRunner {
@Autowired
private EmployeeService employeeService;
@Override
public void run(String... args) throws Exception {
// 검색 조건 생성
EmployeeSearchCriteria criteria = new EmployeeSearchCriteria();
criteria.setFirstName("John");
criteria.setMinSalary(5000.0);
// 동적 SQL 실행
List<Employee> employees = employeeService.getEmployeesByDynamicCondition(criteria);
for (Employee employee : employees) {
System.out.println(employee.getFirstName() + " " + employee.getLastName() + " - " + employee.getSalary());
}
}
}
4. 오늘의 요약
- MyBatis의 동적 SQL은 조건에 따라 유연한 쿼리를 작성하는 데 매우 유용합니다.
- <if> 태그로 조건을 분기하고, <where> 태그로 불필요한 조건을 자동으로 제거할 수 있습니다.
- 검색 조건 객체를 만들어 유지보수가 쉬운 코드를 작성할 수 있었습니다.
반응형
'개발 > 전자정부프레임워크' 카테고리의 다른 글
MyBatis의 동적 SQL 처리 - <if>와 <choose> 태그 (0) | 2024.12.31 |
---|---|
MyBatis에서 반복문 처리 - <foreach> 태그 (0) | 2024.12.31 |
MyBatis를 사용한 Oracle 데이터 페이징 처리 (0) | 2024.12.31 |
Spring Security 커스터마이징 (Custom UserDetailsService 구현) (0) | 2024.12.30 |
Spring Security와 데이터베이스 연동하기 (0) | 2024.12.30 |