[Spring 2일차] Servlet MVC 구조(ibatis 이용)

이경영·2022년 10월 5일
0

스프링부트

목록 보기
2/12

출처: ibatis

ibatis란 무엇일까?

  • SQL Maps 프레임워크는 관계형 DB에 접근할 때 필요한 자바코드를 현저하게 줄일 수 있도록 도와줌.
  • 간단한 xml 서술자를 이용해 자바빈즈를 SQL statement에 맵핑시킴
  • SQL과 비즈니스로직이 분리되어있어 배포 유지보수, 재활용성 뛰어남
  • SQL뿐만 아니라 저장 프로시저까지 IBATIS가 처리가능
  • 파라미터를 기반으로 동적으로 실행할 SQL 지정가능

ibatis의 설정파일

  • SqlMapConfig파일 : 최상단에 위치하며 전체옵션을 설정하고 SQL MAP 파일들의 위치를 설정함.

config.ibatis
sql-map-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

	<properties resource="./config/properties/database.properties" />

	<settings
		cacheModelsEnabled="true"
		enhancementEnabled="true"
		lazyLoadingEnabled="true"
		maxRequests="32"
		maxSessions="10"
		maxTransactions="5"
		useStatementNamespaces="false" />
		
	<transactionManager type="JDBC" >
		<dataSource type="SIMPLE">
			<property name="JDBC.Driver" value="${driverClassName}" />
			<property name="JDBC.ConnectionURL" value="${url}" />
			<property name="JDBC.Username" value="${username}" />
			<property name="JDBC.Password" value="${password}" />
		</dataSource>
	</transactionManager>
	
	<sqlMap resource="./config/sqlmap/Board.xml" />

</sqlMapConfig>
  • SqlMap파일 : 애플리케이션이 DB와 소통하기 위해 제공하는 입력 파라미터 값과 조합되는 매핑구문을 정의함.

config.sqlmap
Board.xml 파일

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap>

 	<!-- 결과 맵 -->
	<resultMap id="selectBoardListResultMap" class="example.dao.Board">
		<result column="BOARD_SEQ" property="boardSeq" />
		<result column="BOARD_TYPE" property="boardType" />
		<result column="TITLE" property="title" />
		<result column="REG_DATE" property="regDate" />
	</resultMap>
	
	<resultMap id="selectBoardResultMap" class="example.dao.Board">
		<result column="BOARD_SEQ" property="boardSeq" />
		<result column="BOARD_TYPE" property="boardType" />
		<result column="CONTENTS" property="contents" />
		<result column="TITLE" property="title" />
		<result column="REG_DATE" property="regDate" />
	</resultMap>
 
	<!-- 게시물 목록 쿼리 -->
	<select id="selectBoardList" resultMap="selectBoardListResultMap">
		SELECT BOARD_SEQ, BOARD_TYPE, TITLE, REG_DATE 
		FROM T_BOARD
		ORDER BY REG_DATE DESC
	</select>
	
	<select id="selectBoard" resultMap="selectBoardResultMap">
		SELECT BOARD_SEQ, BOARD_TYPE, TITLE, CONTENTS, REG_DATE 
		FROM T_BOARD
		WHERE BOARD_SEQ = #boardSeq#
	</select>
	
	<insert id="insertBoard" parameterClass="example.dao.Board">
		INSERT INTO T_BOARD
		(
			BOARD_TYPE,
			TITLE,
			CONTENTS,
			REG_DATE 		
		)
		VALUES
		(
			#boardType#,
			#title#,
			#contents#,
			NOW()
		)
	</insert>

</sqlMap>
  • sqlMapClient API를 이용해 statement를 수행
    - sqlMapClient 인스턴스는 SqlMapClientBuilder를 사용해서 빌드된다.
    이 클래스는 buildSqlMap()이라는 하나의 중요한 정적 메소드를 가진다.
    • buildSqlMap()메소드는 간단하게 sqlMap-config.xml의 내용을 읽을 수 있는 Reader인스턴스를 가져온다.
package example.ibatis;

import java.io.Reader;

import org.apache.ibatis.io.Resources;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class BaseSqlMapConfig {
	
	//sqlmapclient는 최초선언 이후 변경되면 안됨. static 메소드로 접근가능하게 
	private static final SqlMapClient sqlMapClient;
    //여기 안에 있는 메소드 이용해서 xml안의 태그를 호출한다.

	static {
		try {
			String resource = "./config/ibatis/sql-map-config.xml";
			Reader reader = Resources.getResourceAsReader(resource);
			sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
			System.out.println("sqlMapClient : " + sqlMapClient);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("ibatis config error : " + e);
		}
	}

	public static SqlMapClient getSqlMapInstance() {
		return sqlMapClient;
	}

}
  • sqlMapClient는 관련된 모든 매핑된 statement를 수행하기 위한 API를 제공한다.

메소드들은 다음과 같다

queryForList와 queryForObject의 차이점
queryForObject : 1개의 레코드만 가져와 객체에 저장함. 하나 이상 반환되는 경우 예외처리
queryForList : 1개 이상의 레코드를 가져와 자바객체의 List를 만드는데 사용됨.

example.dao
BoardDao

package example.dao;

import java.sql.SQLException;
import java.util.List;

import example.ibatis.BaseSqlMapConfig;

public class BoardDao {

	@SuppressWarnings("unchecked")
	public List<Board> selectBoardList() throws SQLException {
		return BaseSqlMapConfig.getSqlMapInstance().queryForList("selectBoardList");
	}
	
	public Board selectBoard(int boardSeq) throws SQLException {
		return (Board) BaseSqlMapConfig.getSqlMapInstance().queryForObject("selectBoard", boardSeq);
	}
	
	
	public void insertBoard(Board board) throws SQLException {
		BaseSqlMapConfig.getSqlMapInstance()
			.insert("insertBoard", board);
	}
	
}


가상주소 @webservlet 기능

WEB-INF의 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  	<display-name>java-web-02-jsp</display-name>
	
	<servlet>
		<servlet-name>boardList</servlet-name>
		<servlet-class>example.servlet.BoardListServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>boardList</servlet-name>
		<url-pattern>/board/list</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>boardForm</servlet-name>
		<servlet-class>example.servlet.BoardFormServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>boardForm</servlet-name>
		<url-pattern>/board/form</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>boardDetail</servlet-name>
		<servlet-class>example.servlet.BoardDetailServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>boardDetail</servlet-name>
		<url-pattern>/board/detail</url-pattern>
	</servlet-mapping>
	
	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.jsp</welcome-file>
		<welcome-file>default.htm</welcome-file>
	</welcome-file-list>
</web-app>

- SQlMapXML파일

<sql>

refid - <sql>로 생성된 쿼리문을 refid=id로 해서 <include>로 가져온다

profile
꾸준히

0개의 댓글