Spring/스프링 프로젝트

프로젝트 구현 중 Mybatis

어굴애 2021. 6. 29. 02:11
${result.STUDENT_NO}

개념 정리도 제대로 안하고 프로젝트에 들어갔는데, 특히나 마이바티스는 코드를 보고 대충 짐작해서 쓰는 수준이다.

지금은 여유가 없기 때문에 구현부터 하면서 대략적으로 정리해둔 뒤, 나중에 다시 공부하면서 개념을 다시 정리할 예정이다.

 

데이터를 List로 가져오고 싶을때

List임에도 불구하고 type은 객체명을 쓴다.

<select id="DAO의 메소드명" resultType="Member">
	select emp_id, emp_password from member;
</select>

 

Q. ResultMap은 왜 쓰는가?

컬럼명과 클래스의 필드명이 다를 때 둘을 매핑하기 위해 쓴다.

select태그 안에는 resultType대신 resultMap 속성을 쓰고, 상단에 따로 컬럼명과 프로퍼티명(객체의 필드명)을 매핑한다.

 

<resultMap type="Member" id="selectAllMember">
	<result column="emp_id" property="empId"/>
    <result column="emp_password" property="empPw"/>
</resultMap>

<select id="DAO의 메소드명" resultMap="selectAllMember">
	select emp_id, emp_password from member;
</select>

 

대안 1 : resultMap의 type을 객체가 아닌 hashmap으로 준다면, 매핑 과정은 훨씬 단순해진다.

key값을 컬럼명으로 가지는 HashMap이 생성된다.

단, 이때 key값은 뷰단에서 사용할 때 대문자로 가져와야 한다고 한다. 

<resultMap type="hashMap" id="selectMemberMap"></resultMap>

<select id="selectAllMember /*DAO의 메소드명*/" resultMap="selectMemberMap">
	select emp_id, emp_password from member;
</select>


-----뷰단
${result.EMP_PASSWORD}

 

대안 2 :  쿼리문을 작성할 때 as를 이용해 컬럼명과 프로퍼티명을 맞춘다.

<select id="selectAllMember /*DAO의 메소드명*/" resultType="Member">
	select emp_id, emp_password from member;
</select>

 

Q. 그럼 어떻게 ResultMap을 사용하지?

 

 

Q.hashMap은 어떻게 쓰는걸까?

<select id="selectAllMember /*DAO의 메소드명*/" resultType="HashMap">
	select emp_id, emp_password from member;
</select>

--컨트롤러
List<Map<String,String>> list =dao.selectAllMember();

-----뷰단
<c:forEach var="list" items="${list}">
	<tr>
    	<th>${list.emp_id}</th>
        <th>${list.emp_password}</th>
    </tr>
<c:forEach>

 

 

Q. 마이바티스에서 hashMap을 어떻게 표기하는가?

hashMap? hashmap? HashMap? java.util.HashMap?

 

 

Q. 데이터를 List<String>로 가져오고 싶을 때

ResultType에는 List가 올 수 없다고 한다. 배열은 가능하다고 하는데, 보통은 한행씩을 객체에 담는 Map에 담아와서 List로 변환한다.

List<Map<Obj, Obj>>

 

 

도움이 되었던 글1 : 데이터를 가져오는 여러가지 방법

도움이 되었던 글2 : hashMap을 resultType으로 쓰는 법

봐야할 글 : Mybatis에서 resultType지정

 

 


 

본부별 부서리스트(문자열로 변환)을 HashMap으로 가져오기 (Row를 Colum으로 변경)

 

organization 테이블

select org_groupname, group_concat(org_teamname separator '/') as teamList from organization group by org_groupname;


 반복 쿼리 한번에 쓰기: 조건절 같은 부분은 반복되는데, 변수처럼 선언해두고 쓸수 있다고 한다.

 

반복쿼리실행 (insert)

foreach, Hashmap<String, Object> map, List<<Hashmap<String, Object>>>를 모두 사용한다.

예를 들어 user_id에 문자열을 저장하고

item_props라는 하나의 객체에 name, price, id 등 여러가지 문자열 속성을 저장하고 여러 개의 아이템이 존재할 때,

list.add("item1", item); list.add("item2", item2);

map.put("id", user_id);    map.put("items"", list); 와 같은 방식으로 DAO에서 넣은 후 마이바티스에서 forEach문을 사용해 꺼낸다. 자세한 내용은 링크참조

 

 

 

 

https://zorba91.tistory.com/213

 

[문자열 연결 function] MySQL의 group_concat과 oracle의 LISTAGG 사용 방법

컬럼의 데이터들을 연결해서 보여주고 싶을 때가 있다. 예를 들면, 우리 회사의 사업 분야를 row 한 개에 보고 싶다!  comp_name  business_area  zorba  food  zorba  hotel  zorba  car zorba 회사의 사..

zorba91.tistory.com

 

 

 

ForEach