자바 Spring

23-02-06) 마이바티스 Mapper XML의 주요 속성

JadeStone 2023. 2. 6. 17:13

아래의 내용은 반드시 암기해야함.

#select 속성

*resultType 

- sql 기준 반환이 있으면 resultType를 꼭 기재해줘야한다.

- 결과 반환 타입

- 한 행에대한 처리를 할 타입을 적어주면 됨.

  	<!-- ; 은 적지 않습니다  -->
  	<!-- 한 행에 대한 처리를 할 데이터 타입 (풀 경로 다 적어야함)-->
  	<select id="getScore" resultType="com.simple.command.ScoreVO">
  		select * from score
  	</select>

 

*resultMap 

-join할 때 사용

 

*parameterType 

- sql문이 전달 받는 타입

- parameterType 는 생략 가능 (단, 내코드를 보는 다른 사람들을 위해서 기재하면 좋음)

 

# sql 구분의 값의 전달

*  #{name}

- 객체의 경우 중괄호 {} 안에 들어오는 값은 

  객체의 셋터메서드 명이 됨.  

  단, 대소문자 구분은 필요없음

 

# insert, update, delete

*insert(단일값)

인터페이스

public int insertOne(String name);

구현

-파라미터는 생략해도 되지만 이 코드를 볼 다른 사람들이 식별하는데 도움이되게 하기 위해서 기재해주는게 좋다.

  	<!-- parameterType - 매개변수의 타입(생략가능)  -->
  	<insert id="insertOne" parameterType="string">
  		insert into score(name) values(#{name})
  	</insert>

*insert(다중값)

public int insertTwo(ScoreVO vo); //다중값
  	<insert id="insertTwo" parameterType="com.simple.command.ScoreVO">
  		insert into score(name, kor, eng)
  		values(#{name}, #{kor}, #{eng})
  	</insert>

 

 

#마이바티스의 두개이상 데이터 맵핑 처리 (반드시 외우기)

*단일값은 언제든 전달 가능.

public ScoreVO getOne(int a);
  	<!-- 매개변수 - 단일값(매개변수명을 그대로) -->
  	<select id="getOne" resultType="com.simple.command.ScoreVO">
  		select * from score where num = #{a}
  	</select>

 

1. VO클래스 자동맵핑 -> 매개변수에 vo가 들어가면 vo 의 셋터 메서드를 읽어줌

2. HashMap 자동맵핑  -> 정말 부득이한 경우가 아니면 사용하지 않음.

3. @Param 이름지정을 사용해서 맵핑 -> 매개변수에 전달하는 값이 다중값일 때

*마이바티스는 매개변수를 반드시 1개만 받아야함.

그러나 매개변수가 2개 이상이 되는 경우에 강제로 이름을 지정해주어서 사용해야함.

-TestMapper.java 

	//마이바티스는 매개변수를 한개만 받아야함(문법적규칙임)
	public void insertFour(@Param("변수명1") String name, @Param("변수명2") int kor);

-TestMapper.xml 

	<insert id="insertFour">
		insert into score(name, kor) values(#{변수명1}, #{변수명2})
	</insert>

JDBCMybatis.java

	//insert구문 @Param - 매개변수가 2개 이상일 때 매개변수에 이름붙이기
	@Test
	public void testCode11() {
		testMapper.insertFour("파람테스트", 100);
	}

 

 

*mapper 인터페이스 

package com.simple.basic.mapper;

import java.util.ArrayList;
import java.util.Map;

import org.apache.ibatis.annotations.Mapper;

import com.simple.command.ScoreVO;

@Mapper //마이바티스 매퍼를 지칭 - (스프링에서는 생략가능)
public interface TestMapper {
	
	public String getTime(); //1
	public ArrayList<ScoreVO> getScore();
	public ScoreVO getOne(int a);
	
	public int insertOne(String name); //단일값
	public int insertTwo(ScoreVO vo); //다중값
	public int insertThree(Map<String, String> map); //다중값
	
	public Map<String, Object> selectMap(int num); // Map<String, Object> 이거는 한 행만 가져오겠다는 뜻. 3번 키값 조회
	public ArrayList<Map<String, Object>> selectTwo(); //맵을 통한 다중행 조회
	
	public boolean updateOne(ScoreVO vo); //update(3번 업데이트)
}

*mapper 인터페이스 구현 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.simple.basic.mapper.TestMapper">
  	
  	<!-- id는 인터페이스의 메서드명 resultType=반환타입 -->
  	<select id="getTime" resultType="string">
  		select now()
  	</select>
  	
  	<!-- ; 은 적지 않습니다  -->
  	<!-- 한 행에 대한 처리를 할 데이터 타입 (풀 경로 다 적어야함)-->
  	<select id="getScore" resultType="com.simple.command.ScoreVO">
  		select * from score
  	</select>
  	
  	<!-- 매개변수 - 단일값(매개변수명을 그대로) -->
  	<select id="getOne" resultType="ScoreVO">
  		select * from score where num = #{a}
  	</select>
  	
  	<!-- parameterType - 매개변수의 타입(생략가능)  -->
  	<insert id="insertOne" parameterType="string">
  		insert into score(name) values(#{name})
  	</insert>
  	
  	<insert id="insertTwo" parameterType="ScoreVO">
  		insert into score(name, kor, eng)
  		values(#{name}, #{kor}, #{eng})
  	</insert>
  	
  	<insert id="insertThree">
  		insert into score(name, kor, eng)
  		values(#{name}, #{kor}, #{eng})
  	</insert>
  	
  	<select id="selectMap" resultType="map" parameterType="int">
  		select * from score where num = #{num}
  	</select>
  	
  	<select id="selectTwo" resultType="map">
  		select * from score
  	</select>
  	
  	<!-- alias설정이 있다면 parameter타입, result타입에 단축명으로 사용가능합니다. -->
  	<update id="updateOne" parameterType="ScoreVO">
  		update score set name = #{name},
  		  				 kor = #{kor}, 
  		  				 eng = #{eng}
  		where num = #{num}
  	</update>
  	
  </mapper>

* 마이바티스 실행구문( 아래코드는 테스트 파일임)

package com.simple.basic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.simple.basic.mapper.TestMapper;
import com.simple.command.ScoreVO;

@RunWith(SpringJUnit4ClassRunner.class)//junit으로 테스트환경을 구성
@ContextConfiguration("file:src/main/webapp/WEB-INF/config/root-context.xml")//동작시킬 스프링 설정파일
public class JDBCMybatis {
	
//	@Autowired
//	SqlSessionFactoryBean sqlSessionFactory;
//	
//	
//	@Test
//	public void testCode01() {
//	
//		//마이바티스 핵심 객체
//		System.out.println(sqlSessionFactory);
//	}
	
	@Autowired
	TestMapper testMapper;
	
//	@Test
//	public void testCode02() {
//		String time = testMapper.getTime();
//		System.out.println(time);
//	}
	
	//select태그의 resultType
//	@Test
//	public void testCode03() {
//		ArrayList<ScoreVO> list = testMapper.getScore();
//		System.out.println(list.toString());
//	}
	
	//매개변수 - 단일값
//	@Test
//	public void testCode04() {
//		
//		ScoreVO vo = testMapper.getOne(1);
//		System.out.println(vo.toString());
//		
//	}

	//insert - 단일값
//	@Test
//	public void testCode05() {
//		
//		int result = testMapper.insertOne("이순신");
//		System.out.println("성공실패:" + result);
//		
//	}
	
	//insert - 다중값 (vo) - setter가 파라미터가 됩니다.
//	@Test
//	public void testCode06() {
//		
//		ScoreVO vo = new ScoreVO(0, "테스트", "50", "100");
//		int result = testMapper.insertTwo(vo);
//		System.out.println("성공실패:" + result);
//		
//	}
	
	//insert - 다중값 (Map): key값이 파라미터가 됩니다.
	//map은 정말 부득이한 경우에만 사용하도록 하기.
//	@Test
//	public void testCode07() {
//		
//		Map<String, String> map = new HashMap<>();
//		map.put("name", "홍길자");
//		map.put("kor", "30");
//		map.put("eng", "40");
//		
//		int result = testMapper.insertThree(map);
//		System.out.println("성공실패:" + result);
//		
//	}
	
	//select - map타입의 반환
//	@Test
//	public void testCode08() {
//		Map<String, Object> map = testMapper.selectMap(3);
//		System.out.println(map.toString());
//	}
	
	//select - map타입의 반환 : 맵 타입을 사용하는 것은 부득이한 경우만 사용합니다.
//	@Test
//	public void testCode09() {
//		
//		ArrayList<Map<String, Object>> list = testMapper.selectTwo();
//		
//		System.out.println(list.toString());
//		
//	}
	
	//update구문
	@Test
	public void testCode10() {
		ScoreVO vo = new ScoreVO(3, "변경", "100", "100");
		boolean result = testMapper.updateOne(vo);
		System.out.println("성공실패:" + result);
	}
	
	
}

 

#동적쿼리 지원

나중에 공부한다고 하심.

 

<Mybatis 설정 추가하기>

# configLocation 속성

*파일은 자바 리소스 폴더에 xml 파일로 만든다. 

*위에  mapper 를 구현하는 xml 파일에서 

 resultType 나 parameter에 들어오는 객체의 경로를 간단하게 하기 위해서 사용.

 

*mybatis-config.xml 파일

-이걸 꼭 기입해줘야함.

<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

-파일 전체 코드

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">


<!-- 마이바티스 부연 설정 - ScoreVO를 단축명으로 사용 -->
  <configuration>
  	<typeAliases>
  		<typeAlias type="com.simple.command.ScoreVO" alias="ScoreVO"/>
  	</typeAliases>
  </configuration>

*root-contex.xml ( 데이터베이스 설정파일) 에 아래

property 태그 와  위에 xml 파일을 읽어올 수 있도록 경로 설정해줘야함.

 

classpath:/ 는 java/resources 폴더를 지정해줌.

	<!-- 마이바티스설정 sqlSessionFactory 빈으로 생성 -->
	<bean class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 데이터베이스 정보 전달 -->
		<property name="dataSource" ref="ds" />
		<property name="configLocation" value="classpath:/mybatis-config/mybatis-config.xml"/>
	</bean>
	
	<!-- 마이바티스 관련 어노테이션을 찾아서 설정으로 등록 -->
	<mybatis-spring:scan base-package="com.simple.*"/>
	<mybatis-spring:scan base-package="com.simple.basic.mapper"/>

*mpaaper.xml   맵퍼 구현 파일에서  앨리어스만으로 사용가능

  	<!-- alias설정이 있다면 parameter타입, result타입에 단축명으로 사용가능합니다. -->
  	<update id="updateOne" parameterType="ScoreVO">
  		update score set name = #{name},
  		  				 kor = #{kor}, 
  		  				 eng = #{eng}
  		where num = #{num}
  	</update>