개발군싹

3) mybatis 데이터 조회(List) 본문

Mybatis

3) mybatis 데이터 조회(List)

개발자군싹 2023. 12. 4. 19:55

⭐ mybatis를 이용한 데이터 조회

➡️ mybatis를 이용하여 DB에 저장된 데이터를 selectOne, selectList를 이용하여 조회

SELECT 메소드

  • selectOne : select문의 결과가 0~1개 일 때 사용하는 메소드

→ selectOne(”mapper명.sqlid”[,Object])

  • selectList : select문의 결과가 0~1개 이상일 때 사용하는 메소드

→ selectList(”mapper명.sqlid”[,Object,RowBounds])

Mapper에서 <select>태그 이용하기

  • 설정 속성

→ id : sql문 mapping명 설정

→ resultType || resultMap : select문의 결과를 반환할 객체 설정 (둘 중 하나만 설정해서 사용한다.)

resultType : java에서 생성한 클래스 자체를 설정할 때 → package명.클래스명

⇒ resultType : DataBase의 컬럼명과 DTO의 필드명이 같을 때는 naming mapping이 필요없음으로 mybatis가 가지고 있는 타입을 선언하여 데이터 생성할 수 있다.

resultMap : mybatis의 <resultMap>태그로 생성한 것을 설정할 때

⇒ resultMap : DataBase의 컬럼명과 DTO의 필드명이 다르기 때문에 mybatis가 해당 컬럼과 필드가 같을 수 있도록 사용자가 mapping작업을 해줘야한다.


➡️ 예제) jsp에서 학생번호 입력 받아 데이터를 조회하기

Student DTO

private int studentNo;
	private String studentName;
	private String studentTel;
	private String studentEmail;
	private String studentAddress;
	private Date regDate;
<h3>학생번호로 데이터 조회하기</h3>
<form action="${path }/student/searchNo.do">
		<input type="number" name="no"/>
		<input type="submit" value="검색"/>
</form>

** controller와 service, dao에서의 접근은 앞선 학습으로 생략 (필요시 mybatis-Insert예제 참고)

 

<select id="searchStudentByNo" parameterType="_int" resultMap="studentMap">
		<!-- SELECT student_no as studentNo,
			   student_name as studentName,
			   student_tel as studentTel,
			   student_email as studentEmail,
			   student_addr as studentAddress,
			   reg_date as regDate --> Alias를 이용해서도 필드명과 컬럼명을 맵핑할 수 있다. 
		SELECT *
		FROM STUDENT 
		WHERE STUDENT_NO = #{no}
	</select>

<select>태그를 이용하여 select문의 결과를 가져올 수 있다. 학생번호(PK)로 조회하였기에 selectOne()메소드를 이용

⇒ 학생 번호는 int 타입으로 가져와 사용하며 이에 따라 parameterType=”_int”로 설정.

조회 결과를 Student라는 DTO객체에 저장하기 위해서 resultMap을 이용하여 해당 DB의 컬럼명과 DTO의 컬럼명 Mapping 작업이 필요하다.

 

 

<resultMap>

<resultMap type="com.mybatis.model.dto.Student" id="studentMap">
		<id column="student_no" property="studentNo"/>
		<result column="student_name" property="studentName"/>
		<result column="student_tel" property="studentTel"/>
		<result column="student_addr" property="studentAddress"/>
		<result column="student_email" property="studentEmail"/>
		<result column="reg_date" property="regDate"/>
	</resultMap>

➡️ resultMap 태그는 DB데이터와 DTO를 연결해주기 위한 태그, DB의 column과 DTO의 필드를 연결시켜준다.

 

 


⭐ resultMap 자식 태그 종류 및 속성

⇒ DB의 컬럼명과 DTO의 필드명이 같으면 맵핑작업을 할 필요가 없다.

<resultMap id="resultMap이름" type="연결할DTO클래스">
		<id column="" property=""> : pk컬럼을 매핑할 때 사용하는 태그
		<result column="" property=""> : 일반 컬럼을 매핑할 때 사용하는 태그
				
		클래스에 선언된 has a 관계 객체를 매핑할 때 사용
		<association column="" ofType=""||resultMap=""> : 일대일 관계에 있는 객체와 매핑할 때
		<collection column="" ofType=""||resultMap=""> : 일대다 관계에 있는 객체와 매핑할 때
</resultMap>

 


➡️ 예제) 학생 데이터 전체 조회하기

DB에서 가져오는 데이터(ROW)가 여러개 이므로 List를 활용하여 데이터를 가져올 수 있다.

(JDBC와 동일)

** 앞서 번호로 데이터를 조회하면서 작성해둔 resultMap이 있으므로 편리하게 데이터를 가져올 수 있다. (참 편리 하네…JDBC 💢💢)

  • student-mapper.xml - selectStudentAll
<select id="selectStudentAll" resultMap="studentMap">
		SELECT *
		FROM STUDENT
	</select>

 

데이터 조회 관련된 Mapper에서 참고 구문

<select id="selectStudentByName" parameterType="string" resultMap="studentMap">
		SELECT *
		FROM STUDENT
		WHERE STUDENT_NAME LIKE '%'||#{name}||'%'
	</select>

➡️ 학생 이름이 포함된 정보를 조회하는 구문

DB에서의 SQL문

SELECT *

FROM STUDENT

WHERE STUDENT_NAME LIKE ‘%홍길동%’

⇒ 위와 같이 mapper.xml 파일에서 작성해준다.

 

🔥 LIKE 뒤의 작성문을 JAVA코드로 xml에서 작성 시 ‘%’||#{name}||’%’ 로 표기

(java 내에서 사용하므로 String 결합 연산인 ‘+’연산을 사용해 오류를 발생할 수 있다.)

SQL문에서 문자열 결합 연산인 ‘||’를 이용하여 각 문자열로 취급하고 합쳐준다.