티스토리 뷰

 

[ 1. 검색 조건이 있는 SQL문장을 Mapper에 작성하기 ] (*****)

 

	<!-- 1. 게시판 검색어 조건에 맞게, 특정 게시글 번호로 검색해서 반환 1 ( 안전하지 않음 )  -->
    <select id="findBoardByBno" resultType="org.zerock.myapp.domain.BoardVO">
        SELECT bno, title, content, writer, insert_ts, update_ts 
        FROM tbl_board 
        WHERE 

        <if test="bno != null">
            bno = #{bno}
        </if>

    </select>

    <!-- 2. 게시판 검색어 조건에 맞게, 특정 제목으로 검색해서 반환 2 (****) -->
    <select id="findBoardByTitle" resultType="org.zerock.myapp.domain.BoardVO">
        SELECT bno, title, content, writer, insert_ts, update_ts 
        FROM tbl_board 

        <where>

            <if test="title != null">
                title LIKE '%'||#{title}||'%'
                <!-- 와일드 카드로 title로 검색 -->
            </if>

        </where>

    </select>

    <!-- 3. 게시판 검색어 조건에 맞게, 특정 작가로 검색해서 반환 3  -->
    <select id="findBoardByWriter" resultType="org.zerock.myapp.domain.BoardVO">
        SELECT bno, title, content, writer, insert_ts, update_ts 
        FROM tbl_board 

        <trim prefix="WHERE" prefixOverrides="AND | OR">

            <if test="writer != null">
                writer LIKE '%'||#{witer}||'%'
                <!-- 와일드 카드로 writer 검색 -->
            </if>

            <if test="writer != null">
                writer LIKE '%'||#{witer}||'%'
                <!-- 와일드 카드로 writer 검색 -->
            </if>

            <if test="writer != null">
                writer LIKE '%'||#{witer}||'%'
                <!-- 와일드 카드로 writer 검색 -->
            </if>

        </trim>
    </select>

    <!-- 4. 게시판 검색어 조건에 맞게, 특정 게시글 번호와 제목을 검색해서 반환 4  -->
    <select id="findBoardByBnoAndWriter" resultType="org.zerock.myapp.domain.BoardVO">
        SELECT bno, title, content, writer, insert_ts, update_ts 
        FROM tbl_board 

        <!-- 다중 조건식( 체크 조건이 여러개인 경우 )의 처리 -->
        <!-- prefix는 실행될 쿼리의 <trim> 태그 안에 쿼리 가장 앞에 붙여준다. -->
        <!-- prefixOverrides는 조건식이 2개 이상일 때 사용한다. -->
        <!-- prefixOverrides는 실행될 쿼리의 <trim> 문 안에 쿼리 가장 앞에 해당하는 문자들이 있으면 자동으로 지워준다. -->
        <trim prefix="WHERE" prefixOverrides="AND | OR">

            <if test="bno != null">
                bno = #{bno}
            </if>

            <if test="title != null">
                AND title LIKE '%'||#{title}||'%'
            </if>

        </trim>

    </select>

    <!-- 5. 게시판 검색어 조건에 맞게, 특정 게시글 번호 또는 제목을 검색해서 반환 5 (******)  -->
    <select id="findBoardByBnoOrWriter" resultType="org.zerock.myapp.domain.BoardVO">
        SELECT bno, title, content, writer, insert_ts, update_ts 
        FROM tbl_board 

        <!-- switch 문 -->
        <where>

            <choose>

                <when test="bno != null">
                    bno = #{bno}
                </when>

                <when test="title != null">
                    OR title LIKE '%'||#{title}||'%'
                </when>

                <!-- 그렇지 않으면 컨탠츠 내용내에서 검색하라 -->
                <otherwise>
                    content LIKE %||#{content}||'%'
                </otherwise>

            </choose>

        </where>

    </select>

    <!-- 6. 게시판 검색어 조건에 맞게, 특정 게시글 번호를 검색해서 반환 ( 검색어가 여러개 ) 6 (******)  -->
    <select id="findBoardsBySomeBnos" resultType="org.zerock.myapp.domain.BoardVO">
        SELECT bno, title, content, writer, insert_ts, update_ts 
        FROM tbl_board 

        <where>
            
            bno IN

            <!-- ( bno1, bno2, bno3 ... ) -->
            <foreach collection="list" item="bno" index="index" open="(" close=")" separator=",">
                #{bno}
            </foreach>

        </where>
    </select>

 

[ 2. 검색 조건이 있는 SQL문장을 실행하기 ] (***)

 

package org.zerock.myapp.mapper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.Timeout;
import org.zerock.myapp.domain.BoardVO;

import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;

@Log4j2
@NoArgsConstructor

@TestInstance(Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MapperXmlWithConfigXmlTests {
	
	private SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
	private SqlSessionFactory sqlSessionFactory;
	
//	=========================================================================================
	
	@BeforeAll
	void beforeAll() throws IOException {
		
		log.debug("beforeAll() invoked.");
		
		// =================================================
		// 1st. method : CLASSPATH 사용!
		// String mybatisConfigXml = "mybatis-config.xml";
		// log.info("\t + url : " + Resources.getResourceURL(mybatisConfigXml));
		
		// InputStream is = Resources.getResourceAsStream(mybatisConfigXml);
		// InputStream is = Resources.getUrlAsStream(Resources.getResourceURL(mybatisConfigXml).getPath() );
		// =================================================
		// 2nd. method : file path 사용!
		String mybatisConfigXml = "mybatis-config.xml";
		log.info("\t+ url: " + Resources.getResourceURL(mybatisConfigXml));
		
		File f = new File( Resources.getResourceURL(mybatisConfigXml).getPath() );
		FileInputStream is = new FileInputStream(f);
		// =================================================
		
		try( is; ){
			this.sqlSessionFactory = builder.build(is);
			
			Objects.requireNonNull(this.sqlSessionFactory);
			log.info( "\t + sqlSessionFactory : {}", this.sqlSessionFactory );
		} // try - with - resources
		
	} // beforeAll()
	
//	=========================================================================================
	
	// @Disabled
	@Test
	@Order(1)
	@DisplayName("selectAllBoards")
	@Timeout(value=5000, unit=TimeUnit.MILLISECONDS)
	public void selectAllBoards() {
		
		log.info("selectAllBoards() invoked.");
		
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		log.info("\t + sqlSession : {}", sqlSession);
		
		try ( sqlSession; ){
			
			String namespace = "BoardMapper";
			String sqlId = "selectAllBoards";
			
			List <BoardVO> boards = sqlSession.selectList(namespace+"."+sqlId);
			
			Objects.requireNonNull(boards);
			boards.forEach(log::info);
			
		} // try - with - resources
		
	} // selectAllBoards
	
//	=========================================================================================
	

} // end class

 

[ 3. 검색 조건이 있는 SQL문장을 실행하기 - 히카리CP 사용 버전 ] (*****)

 

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.Timeout;
import org.zerock.myapp.domain.BoardVO;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;

@Log4j2
@NoArgsConstructor

@TestInstance(Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MapperXmlWithNOConfigXmlTests {
	
	private SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
	private SqlSessionFactory sqlSessionFactory;
	
//	=========================================================================================
	
	@BeforeAll
	void beforeAll() throws IOException {
		
		log.debug("beforeAll() invoked.");
		
		// ==============================================================
			// 1단계 : HikariCP의 설정 객체를 생성 및 풀에 대한 설정 수행
		// ==============================================================
		
		HikariConfig hikariConfig = new HikariConfig();
		
		hikariConfig.setDriverClassName("net.sf.log4jdbc.sql.jdbcapi.DriverSpy");
		hikariConfig.setJdbcUrl("jdbc:log4jdbc:oracle:thin:@db202204131245_high?TNS_ADMIN=C:/opt/OracleCloudWallet/ATP");
		
		hikariConfig.setUsername("SCOTT");
		hikariConfig.setPassword("Oracle12345678");
		hikariConfig.setMaximumPoolSize(10);
		hikariConfig.setConnectionTimeout(2000); // 밀리세컨드 단위
		hikariConfig.setDataSourceJNDI("jdbc/HikariCP");
		
		// ==============================================================
			// 2단계 : HikariCP 데이터소스 객체 생성 with 설정 객체
		// ==============================================================
		HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
		
		Objects.requireNonNull(hikariDataSource);
		log.info("\t + 1. hikariDataSource : {}", hikariDataSource);
		
		// ==============================================================
			// 3단계 : TX 관리자 생성을 위한 객체 생성
		// ==============================================================
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		log.info("\t + 2. transactionFactory : {}", transactionFactory);
		
		// ==============================================================
			// 4단계 : 마이바틱스 실행환경(Environment) 객체 생성 
		// ==============================================================
		// 매개변수 1 : 실행환경 식별자값 ( id )
		// 매개변수 2 : TX 공장
		// 매개변수 3 : 데이터 소스
		Environment env = new Environment("development", transactionFactory, hikariDataSource);
		log.info("\t + 3. env : {}", env);
		
		// ==============================================================
			// 5단계 : 자바객체 기반의 마이바티스 설정객체 생성
		// ==============================================================
		// 생성자 매개변수 : 위에서 생성한 실행환경 제공
		Configuration mybatisConfig = new Configuration(env);
		log.info("\t + 4. mybatisConfig : {}", mybatisConfig);
		
		// ==============================================================
			// 6단계 : Mapper 인터페이스 등록
		// ==============================================================
		mybatisConfig.addMapper(BoardMapper.class);
		mybatisConfig.addMapper(UserMapper.class);
		
		// ==============================================================
			// 7단계 : 위에서 생성한 설정객체 기반의 SqlSessionFactory 생성
		// ==============================================================
		this.sqlSessionFactory = builder.build(mybatisConfig);
		Objects.requireNonNull(mybatisConfig);
		
		log.info("\t+ 5. sqlSessionFactory: " + this.sqlSessionFactory);
		
	} // beforeAll()
	
//	=========================================================================================
	
	// 1. Select All Boards ( 전체 출력 )
	
	// @Disabled
	@Test
	@Order(1)
	@DisplayName("selectAllBoards")
	@Timeout(value=2000, unit=TimeUnit.MILLISECONDS)
	public void selectAllBoards() {
		
		log.info("selectAllBoards() invoked.");
		
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		log.info("\t + sqlSession : {}", sqlSession);
		
		try( sqlSession; ){
			
			BoardMapper mapper = sqlSession.getMapper(BoardMapper.class);
			log.info("\t + mapper : {}", mapper);
			
			Objects.requireNonNull(mapper);
			
			List<BoardVO> boards = mapper.selectAllBoards();
			boards.forEach(log::info);
			
		} // try - with - resources
		
	} // selectAllBoards
	
//	=========================================================================================
	
	// 2. Select Board ( 하나만 출력 )
	
	// @Disabled
	@Test
	@Order(2)
	@DisplayName("selectBoard")
	@Timeout(value = 2000, unit = TimeUnit.MILLISECONDS)
	public void selectBoard() {
		
		log.info("selectBoard() invoked.");
		
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		log.info("\t + sqlSession : {}", sqlSession);
		
		try ( sqlSession; ) {
			
			BoardMapper mapper = sqlSession.getMapper(BoardMapper.class);
			log.info("\t + mapper : {}", mapper);
			
			Objects.requireNonNull(mapper);
			
			BoardVO board = mapper.selectBoard(176);
			log.info("\t + board : {}", board);
			
		} // try - with - resources
		
	} // selectBoard
	
//	=========================================================================================
	
	@AfterAll
	void afterAll() {
		log.debug("afterAll() invoked.");
	} // afterAll

} // end class
728x90
댓글
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
최근에 올라온 글
Total
Today
Yesterday
공지사항