if서브메뉴-원하는 금액대에 적합한 추천 메뉴 목록 보여주기
config라는 Source Folder를 생성해서
connection-info.properties 파일을 생성하고 mybatis-config.xml파일을 기존에 있던 것을 복사해온다.
connection-info.properties 에는 경로를 따로 작성해주고
mybatis-config.xml 에는 키 값을 넣어서 연결시켜준다.
기존 매퍼를 연결 할 때에는 mapper resource="~~"라고 작성해줬는데, 이번엔 패키지로 지정해준다.
위에서 지정한 똑같은 경로로 소스폴더를 생성하고 기존 MenuMapper.xml을 가져온다.
같은 경로의 같은 이름이어야 하기 때문에 DynamicSqlMapper로 통일 시킨다.
기존 내용들은 지워주고 mapper namespace 경로를 재설정해준다.
기본 자료형으로는 조건문의 값을 비교할 수 없다. HashMap의 key 혹은 DTO의 getter를 이용하여 값을 확인한다.
https://mybatis.org/mybatis-3/ko/configuration.html#typeAliases
MyBatis – 마이바티스 3 | 매퍼 설정
매퍼 설정 마이바티스 XML 설정파일은 다양한 설정과 프로퍼티를 가진다. 문서의 구조는 다음과 같다.: configuration properties 이 설정은 외부에 옮길 수 있다. 자바 프로퍼티 파일 인스턴스에 설정할
mybatis.org
MyBatis 사이트에서 typeAliases를 확인해보면 HashMap의 별칭은 'hashmap'이라고 명명되어있다.
그것에 맞춰 xml에 parameterType을 써줘야한다.
쿼리문을 작성해준 뒤 if문 안에 들어가는 값을 작성해준다.
이 때, gte 는 >=, lte는 <=
< 비교연산자를 인식을 못 하는데, 문자로만 인식할 수 있는 if문 안에 <[! [CDATA[]]>를 작성해준다.
menuResultMap이라는 resultMap과 연결시켜주고 상단에 적어준다.
DynamicSqlmapper.xml 전체코드
<?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.greedy.section01.xml.DynamicSqlMapper">
<resultMap type="com.greedy.common.MenuDTO" id="menuResultMap">
<id property="code" column="MENU_CODE"/>
<result property="name" column="MENU_NAME"/>
<result property="price" column="MENU_PRICE"/>
<result property="categoryCode" column="CATEGORY_CODE"/>
<result property="orderableStatus" column="ORDERABLE_STATUS"/>
</resultMap>
<select id="selectMenuByPrice" parameterType="hashmap" resultMap="menuResultMap">
SELECT
MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
FROM TBL_MENU
WHERE ORDERABLE_STATUS = 'Y'
<if test="price gte 0 and price lte 10000">
<![CDATA[
AND MENU_PRICE < #{ price }
]]>
</if>
<if test="price gt 10000 and price lte 20000">
AND MENU_PRICE BETWEEN 10000 AND # { price }
</if>
<if test="price gt 20000 and price lte 30000">
AND MENU_PRICE BETWEEN 20000 AND # { price }
</if>
<if test="price gt 30000">
AND MENU_PRICE BETWEEN 30000 AND # { price }
</if>
ORDER BY MENU_CODE
</select>
</mapper>
그냥 모르는 부분, 헷갈렸던 부분만 해야겠다...ㅎㅎ
xml파일에서 메뉴 이름이나 카테고리 명으로 검색하는 sql문 작성한건데,
parameterType=SearchCriteria는 mybatis.xml파일에서 typealias를 설정해서 별칭처럼 써준거다.
원래는 com/greedy/section2.. 이런식으로 경로를 써주는 곳임
그리고 '%'가 앞뒤로 들어간다는 것은 저 #{ value }(메뉴이름 검색하는 값)가 앞이든 뒤든 들어가냐는 조건식이다.
카테고리명이 식사냐, 음료냐, 디저트냐 묻는 조건문을 if~ else if~ else 식으로 조건을 걸 수 있다.
sql문에서 아래의 코드처럼 작성된다.
메뉴 혹은 카테고리 코드로 검색, 단 메뉴와 카데고리 둘 다 일치하는 경우도 검색하며, 검색조건이 없는 경우 전체 검색
문제 발생 : 카테고리로 조회하는 경우 where이 붙지 않기 때문에 이렇게 조회할 수 없다.
해결 방법 1. <where> 태그를 이용한다.
- where 태그는 앞에 where로 시작하지 않으면 자동으로 where을 붙여준다.
- 또한 where절 내부에 모두 쿼리문이 추가되지 않는 상황인 경우 where를 무시한다.
- and나 or로 시작을 하게 되면 자동으로 해당 단어를 지워준다.
해결 방법 2. <trim> 태그를 이용한다.
조회 조건에 and 혹은 or로 시작하지 않는 다른 문자로 시작하는 경우
- where 엘리먼트가 기본적으로 처리하는 기능에 추가 규칙을 정의하기 위해 trim 엘리먼트를 제공한다.
- prefix : 처리 후 엘리먼트의 내용이 있으면 가장 앞에 붙여주는 내용을 기술한다.
- prefixOverrides : 처리 후 엘리먼트의 내용 중 가장 앞에 해당하는 문자들이 있다면 자동으로 지워준다.
- suffix : 처리 후 엘리먼트 내에 내용이 있으면 가장 뒤에 붙여준다.
- suffixOverrides : 처리 후 엘리먼트 내용 중 가장 뒤에 해당 문자들이 있다면 자동으로 지워준다.
bind : 변수를 만든 후 바인딩을 한다.
이 때 _parameter가 파라미터로 전달 된 Object를 의미하며, Collection의 경우 get, Object의 경우 getter를 사용한다.
원하는 메뉴 정보만 수정하기
값을 입력한 일부 컬럼만 값을 변경하려고 if 엘리먼트를 이용하였으나
변경할 메뉴 이름을 입력하지 않은 경우 SET이 빠지기 때문에 set 키워드가 누락 되었다는 오류가 발생한다.
또는 set 키워드가 있더라도 , 가 앞에 붙거나 뒤에 붙어 문법적인 오류가 발생한다.
해결 방법 1. <set> 엘리먼트 사용
- <set> 엘리먼트 내부에 내용이 있을 시 set 구문을 자동으로 추가해준다.
- 앞 또는 뒤에 붙은 콤마를 제거해준다.
해결방법 2. <trim> 엘리먼트 사용
위에서 했던 실습들 전체코드
Application
package com.greedy.section01.xml;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import com.greedy.common.SearchCriteria;
public class Application {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("===== 마이바티스 동적 SQL =====");
System.out.println("1. if 확인하기");
System.out.println("2. choose(when, otherwise) 확인하기");
System.out.println("3. foreach 확인하기");
System.out.println("4. trim(where, set) 확인하기");
System.out.println("9. 종료하기");
System.out.print("메뉴를 선택하세요 : ");
int no = sc.nextInt();
switch(no) {
case 1 : ifSubMenu(); break;
case 2 : chooseSubMenu(); break;
case 3 : foreachSubMenu(); break;
case 4 : trimSubMenu(); break;
case 9 : System.out.println("프로그램을 종료합니다."); return;
}
} while(true);
}
public static void ifSubMenu() {
Scanner sc = new Scanner(System.in);
MenuService menuService = new MenuService();
do {
System.out.println("===== if 서브메뉴 =====");
System.out.println("1. 원하는 금액대에 적합한 추천 메뉴 목록 보여주기");
System.out.println("2. 메뉴 이름 혹은 카테고리 명으로 검색하여 메뉴 목록 보여주기");
System.out.println("9. 이전 메뉴로");
System.out.print("메뉴 번호를 입력하세요 : ");
int no = sc.nextInt();
switch(no) {
case 1 : menuService.selectMenuByPrice(inputPrice()); break;
case 2 : menuService.searchMenu(inputSearchCriteria()); break;
case 9 : return;
}
} while(true);
}
private static int inputPrice() {
Scanner sc = new Scanner(System.in);
System.out.print("검색하실 가격의 최대 금액을 입력해주세요 : ");
int price = sc.nextInt();
return price;
}
private static SearchCriteria inputSearchCriteria() {
Scanner sc = new Scanner(System.in);
System.out.print("검색 기준을 입력해주세요(name or category)");
String condition = sc.nextLine();
System.out.print("검색어를 입력해주세요 : ");
String value = sc.nextLine();
return new SearchCriteria(condition, value);
}
public static void chooseSubMenu() {
Scanner sc = new Scanner(System.in);
MenuService menuService = new MenuService();
do {
System.out.println("===== choose 서브메뉴 =====");
System.out.println("1. 카테고리 상위 분류별 메뉴 보여주기(식사, 음료, 디저트)");
System.out.println("9. 이전 메뉴로");
System.out.print("메뉴 번호를 입력하세요 : ");
int no = sc.nextInt();
switch(no) {
case 1 : menuService.searchMenuBySupCategory(inputSupCategory()); break;
case 9 : return;
}
} while(true);
}
private static SearchCriteria inputSupCategory() {
Scanner sc = new Scanner(System.in);
System.out.print("상위 분류를 입력해주세요(식사, 음료, 디저트) : ");
String value = sc.nextLine();
return new SearchCriteria("category", value);
}
public static void foreachSubMenu() {
Scanner sc = new Scanner(System.in);
MenuService menuService = new MenuService();
do {
System.out.println("===== choose 서브메뉴 =====");
System.out.println("1. 랜덤한 메뉴 5개 추출해서 조회하기");
System.out.println("9. 이전 메뉴로");
System.out.print("메뉴 번호를 입력하세요 : ");
int no = sc.nextInt();
switch(no) {
case 1 : menuService.searchMenuByRandomMenuCode(createRandomMenuCodeList()); break;
case 9 : return;
}
} while(true);
}
private static List<Integer> createRandomMenuCodeList() {
Set<Integer> set = new HashSet<>();
while(set.size() < 5) {
//현재 메뉴 번호는 1-21번까지
int temp = ((int) (Math.random() * 21)) + 1;
set.add(temp);
}
List<Integer> list = new ArrayList<>(set);
Collections.sort(list);
return list;
}
public static void trimSubMenu() {
Scanner sc = new Scanner(System.in);
MenuService menuService = new MenuService();
do {
System.out.println("===== trim 서브메뉴 =====");
System.out.println("1. 검색 조건이 있는 경우 메뉴 코드로 조회, 단 없으면 전체 조회");
System.out.println("2. 메뉴 혹은 카테고리 코드로 검색, 단 메뉴와 카데고리 둘 다 일치하는 경우도 검색하며, 검색조건이 없는 경우 전체 검색");
System.out.println("3. 원하는 메뉴 정보만 수정하기");
System.out.println("9. 이전 메뉴로");
System.out.print("메뉴 번호를 입력하세요 : ");
int no = sc.nextInt();
switch(no) {
case 1 : menuService.searchMenuByCodeOrSearchAll(inputAllOrOne()); break;
case 2 : menuService.searchMenuByNameOrCategory(inputSearchCriteriaMap()); break;
case 3 : menuService.modifyMenu(inputChangeInfo()); break;
case 9 : return;
}
} while(true);
}
private static SearchCriteria inputAllOrOne() {
Scanner sc = new Scanner(System.in);
System.out.print("검색 조건을 입력하시겠습니까?(예 or 아니오) : ");
boolean hasSearchValue = "예".equals(sc.nextLine()) ? true : false;
SearchCriteria searchCriteria = new SearchCriteria();
if(hasSearchValue) {
System.out.print("검색할 메뉴 코드를 입력하세요 : ");
String code = sc.nextLine();
searchCriteria.setCondition("menuCode");
searchCriteria.setValue(code);
}
return searchCriteria;
}
private static Map<String, Object> inputSearchCriteriaMap() {
Scanner sc = new Scanner(System.in);
System.out.print("검색할 조건을 입력하세요(category or name or both or null) : ");
String condition = sc.nextLine();
Map<String, Object> criteria = new HashMap<>();
if("category".equals(condition)) {
System.out.print("검색할 카테고리 코드를 입력하세요 : ");
int categoryValue = sc.nextInt();
criteria.put("categoryValue", categoryValue);
} else if("name".equals(condition)) {
System.out.print("검색할 메뉴 이름을 입력하세요 : ");
String nameValue = sc.nextLine();
criteria.put("nameValue", nameValue);
} else if("both".equals(condition)) {
System.out.print("검색할 이름을 입력하세요 : ");
String nameValue = sc.nextLine();
System.out.print("검색할 카테고리 코드를 입력하세요 : ");
int categoryValue = sc.nextInt();
criteria.put("nameValue", nameValue);
criteria.put("categoryValue", categoryValue);
}
return criteria;
}
private static Map<String, Object> inputChangeInfo() {
Scanner sc = new Scanner(System.in);
System.out.print("변경할 메뉴 코드를 입력하세요 : ");
int code = sc.nextInt();
System.out.print("변경할 메뉴 이름을 입력하세요 : ");
sc.nextLine();
String name = sc.nextLine();
System.out.print("변경할 카테고리 코드를 입력하세요 : ");
int categoryCode = sc.nextInt();
System.out.print("판매 여부를 결정해주세요(Y/N) : ");
sc.nextLine();
String orderableStatus = sc.nextLine();
Map<String, Object> criteria = new HashMap<>();
criteria.put("code", code);
criteria.put("name", name);
criteria.put("categoryCode", categoryCode);
criteria.put("orderableStatus", orderableStatus);
return criteria;
}
}
MenuService
package com.greedy.section01.xml;
import static com.greedy.common.Template.getSqlSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import com.greedy.common.MenuDTO;
import com.greedy.common.SearchCriteria;
public class MenuService {
private DynamicSqlMapper mapper;
public void selectMenuByPrice(int price) {
SqlSession sqlSession = getSqlSession();
mapper = sqlSession.getMapper(DynamicSqlMapper.class);
Map<String, Integer> map = new HashMap<>();
map.put("price", price);
List<MenuDTO> menuList = mapper.selectMenuByPrice(price);
if(menuList != null && menuList.size() > 0) {
for(MenuDTO menu : menuList) {
System.out.println(menu);
}
} else {
System.out.println("검색 결과가 존재하지 않습니다.");
}
sqlSession.close();
}
public void searchMenu(SearchCriteria searchCriteria) {
SqlSession sqlSession = getSqlSession();
mapper = sqlSession.getMapper(DynamicSqlMapper.class);
List<MenuDTO> menuList = mapper.searchMenu(searchCriteria);
if(menuList != null && menuList.size() > 0) {
for(MenuDTO menu : menuList) {
System.out.println(menu);
}
} else {
System.out.println("검색 결과가 존재하지 않습니다.");
}
sqlSession.close();
}
public void searchMenuBySupCategory(SearchCriteria searchCriteria) {
SqlSession sqlSession = getSqlSession();
mapper = sqlSession.getMapper(DynamicSqlMapper.class);
List<MenuDTO> menuList = mapper.searchMenuBySupCategory(searchCriteria);
if(menuList != null && menuList.size() > 0) {
for(MenuDTO menu : menuList) {
System.out.println(menu);
}
} else {
System.out.println("검색 결과가 존재하지 않습니다.");
}
sqlSession.close();
}
public void searchMenuByRandomMenuCode(List<Integer> randomMenuCodeList) {
SqlSession sqlSession = getSqlSession();
mapper = sqlSession.getMapper(DynamicSqlMapper.class);
Map<String, List<Integer>> criteria = new HashMap<>();
criteria.put("randomMenuCodeList", randomMenuCodeList);
List<MenuDTO> menuList = mapper.searchMenuByRandomMenuCode(criteria);
if(menuList != null && menuList.size() > 0) {
for(MenuDTO menu : menuList) {
System.out.println(menu);
}
} else {
System.out.println("검색 결과가 존재하지 않습니다.");
}
sqlSession.close();
}
public void searchMenuByCodeOrSearchAll(SearchCriteria searchCriteria) {
SqlSession sqlSession = getSqlSession();
mapper = sqlSession.getMapper(DynamicSqlMapper.class);
List<MenuDTO> menuList = mapper.searchMenuByCodeOrSearchAll(searchCriteria);
if(menuList != null && menuList.size() > 0) {
for(MenuDTO menu : menuList) {
System.out.println(menu);
}
} else {
System.out.println("검색 결과가 존재하지 않습니다.");
}
sqlSession.close();
}
public void searchMenuByNameOrCategory(Map<String, Object> searchCriteria) {
SqlSession sqlSession = getSqlSession();
mapper = sqlSession.getMapper(DynamicSqlMapper.class);
List<MenuDTO> menuList = mapper.searchMenuByNameOrCategory(searchCriteria);
if(menuList != null && menuList.size() > 0) {
for(MenuDTO menu : menuList) {
System.out.println(menu);
}
} else {
System.out.println("검색 결과가 존재하지 않습니다.");
}
sqlSession.close();
}
public void modifyMenu(Map<String, Object> criteria) {
SqlSession sqlSession = getSqlSession();
mapper = sqlSession.getMapper(DynamicSqlMapper.class);
int result = mapper.modifyMenu(criteria);
if(result > 0) {
System.out.println("메뉴 정보 변경에 성공하셨습니다.");
sqlSession.commit();
} else {
System.out.println("메뉴 정보 변경에 실패하셨습니다..");
sqlSession.rollback();
}
sqlSession.close();
}
}
DynamicSqlmapper.java
package com.greedy.section01.xml;
import java.util.List;
import java.util.Map;
import com.greedy.common.MenuDTO;
import com.greedy.common.SearchCriteria;
public interface DynamicSqlMapper {
List<MenuDTO> selectMenuByPrice(int price);
List<MenuDTO> searchMenu(SearchCriteria searchCriteria);
List<MenuDTO> searchMenuBySupCategory(SearchCriteria searchCriteria);
List<MenuDTO> searchMenuByRandomMenuCode(Map<String, List<Integer>> criteria);
List<MenuDTO> searchMenuByCodeOrSearchAll(SearchCriteria searchCriteria);
List<MenuDTO> searchMenuByNameOrCategory(Map<String, Object> searchCriteria);
int modifyMenu(Map<String, Object> criteria);
}
Template
package com.greedy.common;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Template {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSession getSqlSession() {
if(sqlSessionFactory == null) {
String resource = "mybatis-config.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
return sqlSessionFactory.openSession(false);
}
}
SearchCriteria
package com.greedy.common;
public class SearchCriteria {
private String condition;
private String value;
public SearchCriteria() {}
public SearchCriteria(String condition, String value) {
super();
this.condition = condition;
this.value = value;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "SearchCriteria [condition=" + condition + ", value=" + value + "]";
}
}
MenuDTO(생략)
DynamicSqlMapper.xml
<?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.greedy.section01.xml.DynamicSqlMapper">
<resultMap type="com.greedy.common.MenuDTO" id="menuResultMap">
<id property="code" column="MENU_CODE"/>
<result property="name" column="MENU_NAME"/>
<result property="price" column="MENU_PRICE"/>
<result property="categoryCode" column="CATEGORY_CODE"/>
<result property="orderableStatus" column="ORDERABLE_STATUS"/>
</resultMap>
<select id="selectMenuByPrice" parameterType="hashmap" resultMap="menuResultMap">
SELECT
MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
FROM TBL_MENU
WHERE ORDERABLE_STATUS = 'Y'
<if test="price gte 0 and price lte 10000">
<![CDATA[
AND MENU_PRICE < #{ price }
]]>
</if>
<if test="price gt 10000 and price lte 20000">
AND MENU_PRICE BETWEEN 10000 AND #{ price }
</if>
<if test="price gt 20000 and price lte 30000">
AND MENU_PRICE BETWEEN 20000 AND #{ price }
</if>
<if test="price gt 30000">
AND MENU_PRICE BETWEEN 30000 AND #{ price }
</if>
ORDER BY MENU_CODE
</select>
<select id="searchMenu" parameterType="SearchCriteria" resultMap="menuResultMap">
SELECT
MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
FROM TBL_MENU
<if test="condition == 'category'">
JOIN TBL_CATEGORY USING(CATEGORY_CODE)
</if>
WHERE ORDERABLE_STATUS = 'Y'
<if test="condition == 'name'">
AND MENU_NAME LIKE '%' || #{ value } || '%'
</if>
<if test="condition == 'category'">
AND CATEGORY_NAME = #{ value }
</if>
ORDER BY MENU_CODE
</select>
<select id="searchMenuBySupCategory" parameterType="SearchCriteria" resultMap="menuResultMap">
SELECT
MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
FROM TBL_MENU
WHERE ORDERABLE_STATUS = 'Y'
<choose>
<when test="value == '식사'">
AND CATEGORY_CODE IN(4, 5, 6, 7)
</when>
<when test="value == '음료'">
AND CATEGORY_CODE IN(8, 9, 10)
</when>
<otherwise>
AND CATEGORY_CODE IN(11, 12)
</otherwise>
</choose>
ORDER BY MENU_CODE
</select>
<select id="searchMenuByRandomMenuCode" parameterType="hashmap" resultMap="menuResultMap">
SELECT
MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
FROM TBL_MENU
WHERE ORDERABLE_STATUS = 'Y'
AND MENU_CODE IN
<foreach collection="randomMenuCodeList" item="menuCode" open="(" separator=", " close=")">
#{ menuCode }
</foreach>
</select>
<select id="searchMenuByCodeOrSearchAll" parameterType="SearchCriteria" resultMap="menuResultMap">
SELECT
MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
FROM TBL_MENU
<if test="condition != null and condition eq 'menuCode'">
<where>
MENU_CODE = #{ value }
</where>
</if>
</select>
<select id="searchMenuByNameOrCategory" parameterType="hashmap" resultMap="menuResultMap">
SELECT
MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
FROM TBL_MENU
<!-- <if test="nameValue != null">
WHERE MENU_NAME LIKE '%' || #{ nameValue } || '%'
</if>
<if test="categoryValue != null">
AND CATEGORY_CODE = #{ categoryValue }
</if> -->
<!-- <where>
<if test="nameValue != null">
MENU_NAME LIKE '%' || #{ nameValue } || '%'
</if>
<if test="categoryValue != null">
AND CATEGORY_CODE = #{ categoryValue }
</if>
</where> -->
<!-- <trim prefix="WHERE" prefixOverrides="AND | OR">
<if test="nameValue != null">
MENU_NAME LIKE '%' || #{ nameValue } || '%'
</if>
<if test="categoryValue != null">
AND CATEGORY_CODE = #{ categoryValue }
</if>
</trim> -->
<!-- <trim prefix="WHERE" prefixOverrides="AND | OR">
<bind name="namePattern" value="'%' + _parameter.get('nameValue') + '%'"/>
<if test="nameValue != null">
MENU_NAME LIKE #{ namePattern }
</if>
<if test="categoryValue != null">
AND CATEGORY_CODE = #{ categoryValue }
</if>
</trim> -->
<trim prefix="WHERE" prefixOverrides="AND | OR">
<bind name="namePattern" value="'%' + _parameter.get('nameValue') + '%'"/>
<if test="nameValue != null">
MENU_NAME LIKE #{ namePattern }
</if>
<if test="categoryValue != null">
AND CATEGORY_CODE = #{ categoryValue }
</if>
</trim>
</select>
<update id="modifyMenu" parameterType="hashmap">
<!-- UPDATE
TBL_MENU
<if test="name != null and name != ''">
SET MENU_NAME = #{ name }
</if>
<if test="categoryCode != null and categoryCode gt 0">
, CATEGORY_CODE = #{ categoryCode }
</if>
<if test="orderableStatus != null and orderableStatus != ''">
, ORDERABLE_STATUS = #{ orderableStatus }
</if>
WHERE MENU_CODE = #{ code } -->
<!-- UPDATE
TBL_MENU
<set>
<if test="name != null and name != ''">
MENU_NAME = #{ name }
</if>
<if test="categoryCode != null and categoryCode gt 0">
, CATEGORY_CODE = #{ categoryCode }
</if>
<if test="orderableStatus != null and orderableStatus != ''">
, ORDERABLE_STATUS = #{ orderableStatus }
</if>
</set>
WHERE MENU_CODE = #{ code } -->
UPDATE
TBL_MENU
<trim prefix="SET" prefixOverrides=",">
<if test="name != null and name != ''">
MENU_NAME = #{ name }
</if>
<if test="categoryCode != null and categoryCode gt 0">
, CATEGORY_CODE = #{ categoryCode }
</if>
<if test="orderableStatus != null and orderableStatus != ''">
, ORDERABLE_STATUS = #{ orderableStatus }
</if>
</trim>
WHERE MENU_CODE = #{ code }
</update>
</mapper>
'TIL > MyBatis' 카테고리의 다른 글
[MyBatis] crud-javaconfig (0) | 2022.03.15 |
---|---|
[MyBatis] crud-xmlconfig (0) | 2022.03.14 |
[MyBatis] xml사용하지 않고 SqlSessionFactory빌드, xml 사용하기 (0) | 2022.03.14 |