요구사항에 따라서 쿼리가 바뀌는것 - 동적 SQL
마이바티스 안에는 동적 SQL 처리를 할 수 있는 태그가 가능
public List<Schedule> getScheduleListByString(String word){
List<Schedule> list = null;
if(word == null || word.equals("")) {
list = scheduleMapper.selectScheduleList();
}else {
list = scheduleMapper.selectScheduleListByWord();
}
return list;
}
<?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.example.diary.mapper.ScheduleMapper">
<select id="selectScheduleList" resultType="com.example.diary.vo.Schedule">
SELECT *
FROM
schedule
</select>
<select id="selectScheduleListByWord" parameterType="String" resultType="com.example.diary.vo.Schedule">
SELECT *
FROM
schedule
WHERE schedule_memo LIKE CONCAT('%',#{word},'%')
</select>
</mapper>
기존 JDBC 방식
<select id="selectScheduleListByWord" parameterType="String" resultType="com.example.diary.vo.Schedule">
SELECT *
FROM
schedule
<where>
<if test="word != null and word != ''"><!-- test안에는 java변수이다 (표현식을 가지고 있음), 태그안에서는 #{}안해도 됨 -->
schedule_memo LIKE CONCAT('%',#{word},'%')
</if>
</where>
<!-- where안에 if문을 여러개 가질 수 있음 하나라도 true라면 where절이 자동으로 생김 -->
</select>
마이바티스 동적 태그 활용
SELECT *
FROM
schedule
where x < 10
where x < 10
x < 10 같은 등호를 태그로 인식해서
&로 시작하는 특수문자 사용 또는 CDATA[]사용
where문안에서 (where절 밖에서도 쓸 수 있기는 함)
if - 연속성 AND
choose - 비연속성 AND, OR
foreach - 연속성 or -> in연산자로 바꿀 수 있다
foreach문
가독성이 떨어짐
insert에서 추천X 반복된 작업이 계속되면 해킹위험으로 판단해서 막아버림
예를들어 반 in ('a','b','d') 등 선택조건일때 foreach문 주로 사용
SELECT *
FROM student
WHERE ban_name IN('JAVA','SQL')
ORDER BY ban_name
in안에 들어올 수 있는것들의 수가 딱 정해져있으면 정적으로 if문으로 가능 -> 유연성 낮아짐
in안에 반의 값들이 추가되거나 삭제되거나 할 때 fordeach문이 유리
group by 무조건 집계함수를 사용하기 위함
select ban_name
from student
group by ban_name 같이 집계함수 사용하지 않고 중복을없애기 위해서는 사용하지 않음 X
중복제거하는 쿼리
SELECT distinct ban_name
FROM student
동일한 결과가 나온다고 아무쿼리나 사용하면 안됨
매개변수로 배열이 들어오면 찾을 수가 없음
마이바티스는 값이 배열이면 키값이 자동으로 array가 됨
파라미터값이 하나다(String , 랩퍼) -> 변수이름 -> 아무거나 #{아무거나} , #{x} 값이 하나니깐
vo타입인 경우 -> #{필드이름}
Map 타입이면 -> #{key이름}
list면 -> #{0}이거 안됨!!! foreach문 써야됨 list라고 무조건 적어야됨 이름이 list로 자동 설정 그럼 Map으로 받아야됨
배열 -> Map으로 잡아줌
Map으로 잡아주면 진짜 Map이나 list가 들어옴
package com.example.di_aop.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.di_aop.service.StudentService;
import com.example.di_aop.vo.Student;
@Controller
public class StudentController {
@Autowired private StudentService studentService;
@GetMapping("/studentList")
public String studentList(@RequestParam(name="banNames", defaultValue = "") String[] banNames) {//request.getParameterValues()
//banNames가 0이면 모든 학생 출력
System.out.println(banNames.length);
//List<String> bnList = studentService.getBanNameList();
//List<Student> sList = studentService.getStudentListByBan();
return "studentList";
}
}
package com.example.di_aop.service;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.di_aop.mapper.StudentMapper;
import com.example.di_aop.vo.Student;
@Service
public class StudentService {
@Autowired private StudentMapper studentMapper;
public Map<String,Object> getStudentListByBan(String[] banNames){
List<String> bnList = studentMapper.selectBanNameList();
//controller에서 넘어온 매개값을 가공하여 mapper로 전달
List<String> paramList = Arrays.asList(banNames);
if(paramList.size() == 0) {
paramList = bnList; //mapper에서 받아온 반환값을 가공
}
List<Student> sList = studentMapper.selectStudentListByBan(paramList);
Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put("bnList", bnList);
resultMap.put("sList", sList);
return resultMap;
}
}
Mapper (레지스트리, Dao)
컨트로러가 서비스를 호출할때 파라메타를 보내주는데 이 데이터를 가공
controller 원래는 servlet API
Mapper도 반환값을 내놓는데 이 데이터를 가공해서 컨트롤러로 보내줌
Mapper JDBC API
service -> pojo역할
vo -> 전체의 프로그램에서 매개값?왔다갔다 하는 값