KIC/MyBatis

day57 - MyBatis(parameterType, resultType)

바차 2021. 9. 3. 12:19
반응형

 

[parameterType]

- 마이바티스에서 parameterType 속성을 사용해서 해당 파라미터의 자료형을 명시해준다. 위에서는 student 객체에 결과가 담긴다. student는  미리 생성해둔 Model 객체이다.

 

[resultType]

-  select 된 데이터를 반환할 그릇을 의미한다고 한다.

 

 

 

-> 즉  parameterType으로 col 과 value가 Map 자료형임을 명시하고

-> resultType으로 결과 값이 student 객체에 담길 것이라는 의미

 

 

 

[#{}]

- #{} 사용시 PreparedStatement 생성되고 PreparedStatement 매개 변수 값 안전하게 설정한다.


- PreparedStatement 가 제공하는 set 계열의 메소드를 사용하여 (?)를 대체할 값을 지정한다.

- 데이터 문자열을 자동으로 인식하기 때문에 자동 따옴표 붙인다.

 

- 쿼리 주입을 예방할 수 있어서 보안 측면에서 유리하다.

 

 

[${}]

- ${} 사용시 Statement 생성하고 Statement 매개변수 값 그대로 전달한다.

 

- 전달한 문자열에 따옴표가 붙지 않는다.

 

- 테이블이나 컬럼명을 파라미터로 전달하고 싶을 때 사용한다.

 

- ORDER BY 함수를 사용할 때 자동 따옴표가 붙으면 함수가 안먹기 때문에 ${}를 써야한다고 한다.

 

- 쿼리 주입을 예방할 수 없어서 보안 측면에서는 불리하다.

 

 

[StudentMapper2.xml]

<?xml version="1.0" encoding="UTF-8" ?>
<!-- /src/mapperXML/StudentMapper2.xml --> 
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="student2">

<select id="select" resultType="student">
	select * from student

</select>

<select id="select2" resultType="student" parameterType="map">
	select * from student
	<where>
		<if test="grade !=null"> grade=#{grade}</if>
		<if test="height !=null">height >= #{height}</if>
		<if test="studno !=null">studno = #{studno}</if>
	</where>
</select>


<!-- map 에서 내가 원하는 컬럼을 골라 사용 가능 하도록 where ${col} = #{value}로 지정 -->
<select id="select3" resultType="student" parameterType="map">
	select * from student
		where ${col} = #{value}
</select>

<select id="select4" resultType="student" parameterType="map">
	select ${col} from student
</select>

<select id="select5" resultType="student" parameterType="map">
	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>
</select>

<select id="select6" resultType="student" parameterType="map">
	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>
		<if test="weight != null"> and weight >= #{weight}</if>
	</trim>
</select>

<select id="select7" resultType="student" parameterType="map">
	select * from student
	<if test="datas !=null">
	where ${col} in
	<foreach collection="datas" item="d" separator=","
		open="("  close=")">#{d}
	</foreach>
	</if>
		
</select>

</mapper>

 

[Main3StudentXML.java]

package main;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import model.Student;

public class Main3StudentXML {
	private final static String NS = "student."; 
	private static Map map = new HashMap(); 
	public static void main(String[] args) {

		SqlSessionFactory sqlMap = Main1.initMybatis(); 
		SqlSession session = sqlMap.openSession();
		
		System.out.println("student table 추가");
		Student s= new Student();
		s.setStudno(1111);
		s.setName("케이아");
		s.setGrade(1);
		s.setId("kic001");
		s.setJumin("1111111111");
		s.setDeptno1(101);
		
//		int cnt = session.insert(NS+"insert" , s);
//		System.out.println("student record 추가: " + cnt);
//		session.commit();
		
		s.setGrade(2);
		s.setWeight(60);
		s.setHeight(180);
		s.setProfno(2222);
		s.setStudno(1111);
		
//		int cnt = session.update(NS + "update", s);
//		System.out.println("student record 수정: " + cnt);
//		session.commit();
		
//		int cnt = session.delete(NS + "delete", 1111);
//		System.out.println("student record 삭제: " + cnt);
//		session.commit();
		

		
		//전체 뽑기
		//List<Student> li = session.selectList (NS+"select" , s);
		
		// 1111만 선택해 뽑기
		List<Student> li = session.selectList (NS+"select" , 1111); 
		System.out.println("student row count: "+li.size());

		for (Student st : li) {
			System.out.println(st);
		}
		
		li = session.selectList(NS + "selectRMap");
		System.out.println("student row count: "+li.size());
		for (Student st : li) {
			System.out.println(st);
		}
	}
}

 

 

[Main4StudentXML.java]

package main;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import model.Student;

public class Main4StudentXML {
	// 수정 사항
	//1, config.xml에 <mapper resource="mapperXML/StudentMapper2.xml"/>를 추가해줘야 한다.
	//2. StudentMapper2 의 namespace와 NS ="student2."가 같아야 한다.
	//3. parameterType가 아니라 resultType="student" 로 수정해야 한다.
	private final static String NS ="student2.";
	private static Map map = new HashMap();
	
	public static void main(String[] args) {
		SqlSessionFactory sqlMap = Main1.initMybatis(); 
		SqlSession session = sqlMap.openSession();
		List<Student> li = session.selectList (NS+"select"); 
//		
//		Student s= new Student();
//		System.out.println("student row count: "+li.size());
//
//		for (Student st : li) {
//			System.out.println(st);
//		}
		
		
		
		//map.put("grade", 1);
		//map.put("height", 180);
		map.put("studno", 9711);
		li = session.selectList(NS+"select2", map);
		System.out.println("student row count: "+li.size());
		for (Student st : li) {
			System.out.println(st);
		}
		
		System.out.println("=====================================================");
		
		// 이렇게 내가 원하는 컬럼을 골라 사용 가능
		map.clear();
		map.put("col", "height");
		map.put("value", 180);
		
//		map.put("col", "weight");
//		map.put("value", 70);
		li = session.selectList(NS+"select3", map);
		System.out.println("student row count: "+li.size());
		for (Student st : li) {
			System.out.println(st);
		}
		
		map.clear();
		map.put("col", "name");
		li = session.selectList(NS+"select4", map);
		System.out.println("student row count: "+li.size());
		for (Student st : li) {
			System.out.println(st);
		}
		
		System.out.println("=====================================================");
		
		
		map.clear();
		//map.put("grade", "1");
		map.put("height", 170);
		li = session.selectList(NS+"select5", map);
		System.out.println("student row count: "+li.size());
		for (Student st : li) {
			System.out.println(st);
		}
		
		
		System.out.println("=====================================================");
		
		
		map.clear();
		map.put("grade", "1");
		map.put("height", 170);
		map.put("height", 60);
		li = session.selectList(NS+"select6", map);
		System.out.println("student row count: "+li.size());
		for (Student st : li) {
			System.out.println(st);
		}
		
		
		
		System.out.println("=====================================================");
		List<Integer> ali = Arrays.asList(101, 201);
		map.clear();
		map.put("col", "deptno1");
		map.put("datas", ali);
		li = session.selectList(NS+"select7", map);
		System.out.println("student row count: "+li.size());
		for (Student st : li) {
			System.out.println(st);
		}

	}
}

 

300x250