수업(국비지원)/Mybatis
[MYBATIS] Mybatis DB조회
byeolsub
2023. 4. 21. 21:02
📌 Main2.java
package main;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import mapper.StudentMapper;
import mapper.StudentMapper2;
public class Main2 {
private static SqlSessionFactory sqlMap;
static { //static 초기화 블럭
//바이트형 입력 스트림.
InputStream input = null;
try {
input = Resources.getResourceAsStream("mapper/mybatis-config.xml");
} catch(IOException e) {
e.printStackTrace();
}
//sqlMap : Mybatis 설정 객체
sqlMap = new SqlSessionFactoryBuilder().build(input);
}
private static Class<StudentMapper2> cls = StudentMapper2.class;
private static Map<String,Object> map = new HashMap<>();
public static void main(String[] args) {
SqlSession session = sqlMap.openSession();
System.out.println("1학년 학생 중 키가 175 이상인 학생의 정보");
map.clear();
map.put("grade",1);
map.put("height", 175);
List<Student> list = session.getMapper(cls).select(map);
// List<Student> list = session.getMapper(cls).select2(map);
// List<Student> list = session.getMapper(cls).select3(map); //SQL: select * from student where grade = ? where height >= ? 오류발생
for(Student s : list) System.out.println(s);
System.out.println("키가 175 이상인 학생의 정보");
map.clear();
map.put("height", 175);
// list = session.getMapper(cls).select(map);
// list = session.getMapper(cls).select2(map);
list = session.getMapper(cls).select3(map);
for(Student s : list) System.out.println(s);
System.out.println("2학년 학생의 정보");
map.clear();
map.put("grade",2);
// list = session.getMapper(cls).select(map);
// list = session.getMapper(cls).select2(map);
list = session.getMapper(cls).select3(map);
for(Student s : list) System.out.println(s);
System.out.println("모든 학생의 정보");
// list = session.getMapper(cls).select(null);
// list = session.getMapper(cls).select2(null);
list = session.getMapper(cls).select3(null);
for(Student s : list) System.out.println(s);
//===========================================================
System.out.println("101,201,301 학과에 속한 학생의 정보"); //select * from student where deptno1 in(101,201,301)
map.clear();
List<Integer> depts = Arrays.asList(101,201,301);
map.put("datas", depts);
map.put("columns","deptno1");
list = session.getMapper(cls).select4(map);
for(Student s : list) System.out.println(s);
System.out.println("학과2가 101,201,301 학과에 속한 학생의 정보");
map.clear();
depts = Arrays.asList(101,201,301);
map.put("datas", depts);
map.put("columns","deptno2");
list = session.getMapper(cls).select4(map);
for(Student s : list) System.out.println(s);
System.out.println("학생의 이름이 이서진, 구유미,일지매인 학생의 정보");
map.clear();
List<String>mlist = Arrays.asList("이서진","구유미","일지매");
map.put("datas", mlist);
map.put("columns","name");
list = session.getMapper(cls).select4(map);
for(Student s : list) System.out.println(s);
}
}
📌 StudentMapper2.java -interface로 생성
package mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Select;
import main.Student;
/*
* 같은 이름을 가진 메서드가 여러개 존재 불가 : Mybatis에서 실행 시 오류 발생
* 오버로딩이 불가능 하다.
* 메서드의 이름 : sql구문을 구분 할 수 있는 이름.
*/
public interface StudentMapper2 {
@Select({"<script>",
"select * from student ",
"<choose>"
+ "<when test='grade != null and height != null'>"
+ " where grade = #{grade} and height >= #{height}</when>"
+ "<when test='grade != null'>where grade=#{grade}</when>"
+ "<when test='height != null'>where height >= #{height}</when>"
+ "</choose>",
"</script>"})
List<Student> select(Map<String, Object> map);
/*
* <trim prefix='where' prefixOverrides='AND||OR'>
* trim : 맨 앞에 있는 문자가 AND 또는 OR 일 경우 where로 바꿔라
*
* 1. map : grade:1, height:175
*
* select * from student
* where grade = #{grade}
* and height >= #{height}
*
* 2. map : height:175
*
* select * from student
* where height >= #{height}
*
* 3. map : grade:2
*
* select * from student
* where grade = #{grade}
*
* 4. map : null
*
* select * from student
*/
@Select({"<script>",
"select * from student ",
"<trim prefix='where' prefixOverrides='AND||OR'>",
"<if test='grade != null'>and grade = #{grade}</if>",
"<if test='height != null'>and height >= #{height}</if>",
"</trim>",
"</script>"
})
List<Student> select2(Map<String, Object> map);
//grade,height 중 한개만 입력 될 때 사용되는 동적 sql 구문
@Select({"<script>",
"select * from student ",
"<if test='grade != null'>where grade = #{grade}</if>",
"<if test='height != null'>where height >= #{height}</if>",
"</script>"
})
List<Student> select3(Map<String, Object> map);
/*
* datas :[101,201,301]
* columns : "deptno1"
*
* select * from student where ${columns} in (101,201,301);
*
* datas : ["이서진","구유미","일지매"]
* columns : "name"
*
* select * from student where name in('이서진','구유미','일지매');
*/
@Select({"<script>",
"select * from student ",
"<if test='datas != null'>where ${columns} in",
"<foreach collection='datas' item='d' separator=',' open='(' close=')'>#{d}</foreach></if>",
"</script>"
})
List<Student> select4(Map<String, Object> map);