국비지원학원/MyBatis

112일차-MyBatis

초코맛 2019. 4. 17. 03:27
반응형

 

//에러는 console의 문장 맨뒤만 보면된다..!
//설정용xml은 DB연동 정보+사용할 Mapper
//쿼리가 있는 xml은 mapper.xml id가 중요한데 id가 없다~~그러면 얘를 본다.
//설정파일을 모르갰다~!그러면 코드를 봐준다. (src하위 부터) ss.insert("id")이기 때문에 아이디가 없다~그러면 여기도 확인해 준다.
//mapper안에 들어가는 타입 두가지로는
//parameterType=" VO  " //외부의 값을 내부로 전달할 때  //=>insert,update,delete,select 다
//resultType="  Domain  " //조회 결과를 외부로 내보낼 때 //=>select
                            //=>공통으로 패키지명.클래스명 사용가능하다+java의 data type도 가능하다
//여러번 사용되고 이름이 길다 싶으면 설정용xml에 <typeAlias type="id(객체명)" alias="사용할클래스명"/> 
//그럼 VO와 Domain자리에 사용할 클래스명을 넣으면 된다.!

//select id="아이디" 가 중복된다면 name을 주어서 사용(?)
<select id="아이디" parameterType="기본형|VO(전달된 파라메터 변수)" resultType="도메인(조회된 컬럼과 일치하는 setter를 myBatis에서 찾아 호출">    
                                |parameterMap="Map"(쓰지않는걸 권고)                    |resultMap="mapID"
    select 컬럼명,,,
    from 테이블명
    where 컬럼명 =#{}(기본형,VO) | ${}((VO)
</select>

*resultMap
<resultMap>
 : 조회하는 컬럼과 doamin setter를 미리 매핑시키는 일을 함. (양쪽에서)사용할때에만 사용!! 혼용은 안된다!(힌트로 빨리찾..?)

<resultMap id="mapID" type="패키지명.domain명">
    <result column="컬럼명(대소문자 구분x)" property="setter명(대소문자 구분O)"/>
    ...
</resultMap
//exam_mapper1.xml 에 정의한다.
<!-- Emp Domain을 resultMap으로 설정 -->
<resultMap type="kr.co.sist.exam.domain.Emp" id="empResult">
     <result column="EMPNO" property="empno"/>
     <result column="ename" property="ename"/>
     <result column="job" property="job"/>
     <result column="sal" property="sal"/>
     <result column="hiredate" property="hiredate"/>
     <result column="mgr" property="mgr"/>
</resultMap>
<!-- Zipcode Domain을 더 빨리 찾기 위해 컬럼과 매핑 -->
<resultMap type="kr.co.sist.exam.domain.Zipcode"  id="zipcodeResult">
     <result column="zipcode" property="zipcode"/>
     <result column="sido" property="sido"/>
     <result column="gugun" property="gugun"/>
     <result column="dong" property="dong"/>
     <result column="bunji" property="bunji"/>
</resultMap>

//그리고 아래에서 id를 사용


주의)
//도메인에는 생성자를 만들면 안된다


*중복쿼리의 처리(모든 중복에 사용가능)
사용법) mapper에 정의
<sql id="아이디">
중복쿼리
</sql>

중복쿼리가져다 사용)
<include refid="아이디"/>
//mapper.xml에 정의
<!-- 중복쿼리의 정의 : 위치는 상관이 없당 또한 어느 절이 들어가도  사용가능 -->
<sql id="empDup">
SELECT EMPNO,ENAME,JOB,SAL,MGR,TO_CHAR(HIREDATE,'YYYY-MM-DD Q')  HIREDATE
FROM EMP
</sql>

<!-- 동일 쿼리의 처리 사용 -->
<select id="multiColumnRow" resultMap="empResult"  parameterType="int">
       <include refid="empDup"/>
       WHERE DEPTNO=#{deptno1}
</select>



*카카오 개발 센터(지도)
지도의 중심을 바꾸려면 위도와 경도가 필요한데 구글지도에서 가능

원하는 주소를 찍어 궁금해요?를 누르면 위도 경도 주소를 얻을수 있당


카카오 개발자 센터

카카오 API 설명
=>like.jsp에 들어있당 다음주에 이어서 주소누르면 지도 에 뜨게 할 예정

<<<미완>>
//mybatis_config.xml
<?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">
  <!-- MyBatis의 환경설정(연동할 DB에 대한 설정)을 수행하는 xml
           설정 정보를 properties에 넣고 하는 것과
           설정 정보를 직접 Hard Coding하는 방법 2가지.
   -->
<configuration>
<properties resource="properties/database.properties"/>
<typeAliases>
     <typeAlias type="kr.co.sist.exam.domain.DeptInfo"  alias="di"/>
</typeAliases>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${userid}"/>
        <property name="password" value="${userpass}"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 쿼리문을 가진 XML을 연결(*:0~n개) -->
  <mappers>
    <mapper resource="kr/co/sist/exam/mapper/exam_mapper1.xml"/>
    <mapper resource="kr/co/sist/exam/mapper/exam_mapper2.xml"/>
  </mappers>
</configuration>
//exam_mapper1.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">
  <!-- Query문을 정의
        namespace=ns: XML내에서 중복된 id를 사용할 수 있도록  구분하는 것.
                             (자바의 패키지와 비슷한 용도)
           select 안에 ; 절대 사용하지 않는다!!!
  -->
<mapper namespace="kr.co.sist.exam1">
<!-- Emp Domain을 resultMap으로 설정 -->
<resultMap type="kr.co.sist.exam.domain.Emp" id="empResult">
     <result column="EMPNO" property="empno"/>
     <result column="ename" property="ename"/>
     <result column="job" property="job"/>
     <result column="sal" property="sal"/>
     <result column="hiredate" property="hiredate"/>
     <result column="mgr" property="mgr"/>
</resultMap>
<!-- Zipcode Domain을 더 빨리 찾기 위해 컬럼과 매핑 -->
<resultMap type="kr.co.sist.exam.domain.Zipcode"  id="zipcodeResult">
     <result column="zipcode" property="zipcode"/>
     <result column="sido" property="sido"/>
     <result column="gugun" property="gugun"/>
     <result column="dong" property="dong"/>
     <result column="bunji" property="bunji"/>
</resultMap>
<!-- 중복쿼리의 정의 : 위치는 상관이 없당 또한 어느 절이 들어가도  사용가능 -->
<sql id="empDup">
SELECT EMPNO,ENAME,JOB,SAL,MGR,TO_CHAR(HIREDATE,'YYYY-MM-DD Q')  HIREDATE
FROM EMP
</sql>
<!-- 컬럼하나에 레코드 하나 조회 할 때 -->
<!-- MyBatis에서는 Java의 데이터형(기본형,참조형)을 그대로 사용할  수 있다.
      String data=SqlSession.selectOne("singleColumn"); //을  찾으면 DNAME이 문자열로 나온다.찾기만 하면 return이 된다.
-->
     <select id="singleColumn" resultType="String">
        SELECT DNAME
        FROM DEPT
        WHERE DEPTNO=10
     </select>
<!-- 컬럼하나에 레코드 여러개 조회 할 때
      resultType="자바 데이터형(기본형,참조형)"
      호출 : List<데이터형> list=SqlSession.selectList("id");
      기본형을 사용해도 되고, 기본형에 대응되는 클래스 -  (래퍼)Wrapper class를 사용할 수 있다.
-->
<!-- <select id="multiRow" resultType="int"> -->
     <select id="multiRow" resultType="Integer">
       select deptno
       from dept
     </select>
     
<!-- 컬럼여러개 레코드 하나 조회 할 때 -->  
<!-- <typeAlias>: Domain이나 VO를 미리 등록(iBATIS-mapper에  정의->MyBatis-설정파일에 정의)해 두고 짧은 이름으로 사용할 때  사용한다.
     자주 쓰면 편하당(여러번 사용되면 유리하고 한번만 사용된다면  안쓰는게 낫겠다)
     
     조회되는 컬럼은 대소문자를 구분하지 않지만 setter method는  대소문자를 구분한다.
     iBATIS에서는 컬렴명 또는 컬럼명 as setter명 으로  사용가능?했다?
     
     resultType="패키지명.Domain명 사용되거나 typeAlias의 id가  사용된다."
-->  
     <select id="multiColumn"  resultType="kr.co.sist.exam.domain.DeptInfo">
     <!-- <select id="multiColumn" resultType="di"> -->
       SELECT DNAME,LOC
       FROM DEPT
       WHERE DEPTNO=10
     </select>
<!-- 컬럼여러개 레코드 여러개 조회 할 때
       입력되는(parameterType="") 부서번호에 따른 사원정보  조회(resultType)
       
       입력되는 값이 단일형 이라면 - 자바 데이터형 그냥 사용가능
                                 노드안에서 사용할 때에는  #{아무말대잔치}
      입력되는 값이 복합 형이라면 - VO사용
                                노드안에서 사용할 때에는  #{getter명}(바인드변수가 들어간다"안붙힘!Error남),  ${getter명}("값"이 푹박히고)
      mapper는 읽어들여 실행하기 때문에 앞에 설정파일에서  찾지못하거나 에러나면 읽어들이지 못한다.
      
      조회결과를 미리 매핑한 <resultMap>을 선언 했다면  <select>에서 resultMap속성을 사용해야 한다.
       WHERE DEPTNO=#{deptno1}이때에는 아무말이 들어가도 int로  들어가는게 들어가 상관없지만
-->  
<!-- 동일 쿼리의 처리 <sql>-->  
<!-- <select id="multiColumnRow"  resultType="kr.co.sist.exam.domain.Emp" parameterType="int"> -->
<!-- <select id="multiColumnRow" resultType="empResult"(타입이  일치하지 않아 찾지 못한다) parameterType="int"> -->
     <select id="multiColumnRow" resultMap="empResult"  parameterType="int">
       <include refid="empDup"/>
       WHERE DEPTNO=#{deptno1}
     </select>
<!-- 조회컬럼이 여러개인 경우
      parameterType에 VO를 설정하고 #{getter명}, ${getter}를  사용한다.
      입력되는(parameterType="") 부서번호와 에 따른 사원정보  조회(resultType)
       WHERE DEPTNO=#{deptno} and job=#{job}여기에 deptno에는  반드시 getter이어야 한다.1붙으면 Error
-->
<select id="multiParam" parameterType="kr.co.sist.exam.vo.EmpVO"  resultMap="empResult">
       <include refid="empDup"/>
       <!-- SELECT  EMPNO,ENAME,JOB,SAL,MGR,TO_CHAR(HIREDATE,'YYYY-MM-DD Q')  HIREDATE -->
       <!-- FROM EMP -->
       WHERE DEPTNO=#{deptno} and job=#{job}
</select>
  
<!-- < 의 조회
     사원테이블에서 입력된 연봉보다 적게 받는 사원의 사원번호,  사원명,직무,매니저번호,입사일을 조회하세요
     
     '<'는 직접 사용할 수 없다. &lt;로 사용.
     '<'를 직접 사용하고 싶다면 CDATA Section을 사용한다.
     CDATA Section 사이는 노드가 아닌 단순 문자열임을 알려주는  것.이라 Error안남.
     <![CDATA[
        CDATA Section
     ]]>
     으로 사용한다.
-->  
<select id="lessThan" resultMap="empResult"  parameterType="Integer">
     <include refid="empDup"/>
     <!-- where sal <![CDATA[<]]> #{sal} -->
     <![CDATA[
        where sal < #{sal}
     ]]>
</select>
<!-- > 의 조회
사원테이블에서 입력된 연봉보다 많이 받는 사원의 사원번호,  사원명,직무,매니저번호,입사일을 조회하세요
바로 사용해도 에러는 나지 않지만 권장하는 방법은 아니다.
>는 에러가 발생하지 않는다. &gt; <![CDATA[>]]> 다 가능!
직관성이  떨어지는게 단점
-->  
<select id="greaterThan" resultMap="empResult"  parameterType="Integer">
     <include refid="empDup"/>
        where sal &gt; #{sal}
        order by sal desc
</select>
<!-- like의 조회
     동을 입력받아(parameterType="") 우편번호,시도,구군,동,번지를  조회(resultType="domainclasspullpath"|resultMap="resultMapID")
     
     %#{dong}%면 바인드 변수로 인식하지 못해 Error 난다. 문자열로  바꾸어 해주면 가능!
-->  
<select id="like" resultMap="zipcodeResult"  parameterType="String">
     select zipcode,sido,gugun,dong,nvl(bunji,' ') bunji
     from zipcode
     where dong like #{dong}||'%'
</select>
<!-- subquery의 조회 -->  
<!-- union의 조회 -->  
<!-- join의 조회 -->  
<!-- join+subquery 의 조회 -->  
<!-- 컬럼명 또는 테이블명이 동적일 때의 조회 -->  
<!-- dynamic query : where,if,choose,foreach -->  
  
</mapper>
//main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"  href="http://localhost:8080/mybatis_prj/common/main_v190130.css"/>
<style type="text/css">
#wrap{margin:0px auto;width:800px; height:860px;}
#header{width:800px; height:140px; background:#FFFFFF  url(http://localhost:8080/mybatis_prj/common/images/header_bg.png) repeat-x;
           position: relative; }
#headerTitle{font-family: HY견고딕,고딕; font-size:35px;  font-weight:bold; text-align:center;
                /* padding-top: 35px */ position:absolute;  top:40px; left:290px; }
#container{width:800px; min-height: 600px; }
#footer{width:800px; height:120px; }
#footerTitle{float: right; font-size:15px; padding-top:20px;  padding-right:20px; }
</style>
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
      
});//ready
</script>
</head>
<body>
<div id="wrap">
     <div id="header">
           <div id="headerTitle">SIST Class4</div>
           <div style="padding-top:100px; ">
           <c:import url="/common/jsp/main_menu.jsp"></c:import>
           </div>
     </div>
     <div id="container">
     <c:if test="${not empty param.page}">
     <c:import url="${param.page}.jsp"/>
     </c:if>
     
     </div>
     <div id="footer">
           <div id="footerTitle">copyright&copy; all right  reserved. class 4.</div>
     </div>
</div>
</body>
</html>
//main_menu.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- smartmenu 시작 -->
   <!-- SmartMenus core CSS (required) -->
   <link  href="http://localhost:8080/mybatis_prj/common/smartmenu/css/sm-core-css.css" rel="stylesheet" type="text/css" />
   
   <!-- "sm-blue" menu theme (optional, you can use your own  CSS, too) -->
   <link  href="http://localhost:8080/mybatis_prj/common/smartmenu/css/sm-simple/sm-simple.css" rel="stylesheet" type="text/css" />
   
   <!-- jQuery -->
    <!-- <script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> -->
    <!-- SmartMenus jQuery plugin -->
    <script type="text/javascript"  src="http://localhost:8080/mybatis_prj/common/smartmenu/jquery.smartmenus.js"></script>
    <!-- SmartMenus jQuery init -->
    <script type="text/javascript">
       $(function() {
          $('#main-menu').smartmenus({
             subMenusSubOffsetX: 1,
             subMenusSubOffsetY: -8
          });
       });
    </script>
<!-- smartmenu 끝 -->
     <nav id="main-nav">
      <!-- Sample menu definition -->
      <ul id="main-menu" class="sm sm-simple">
        <li><a href="#void">홈으로</a></li>
        <li><a href="#void">쿼리 실행</a>
          <ul>
            <li><a href="#void">1일차</a>
              <ul>
                <li><a  href="main.jsp?page=day0404/single_column">컬럼하나에 레코드  하나</a></li>
                <li><a  href="main.jsp?page=day0404/multi_column">컬럼여러개에 레코드  하나</a></li>
                <li><a  href="main.jsp?page=day0404/multi_row">컬럼하나에 레코드  여러개</a></li>
              </ul>
            </li>
            <li><a href="#void">2일차</a>
              <ul>
                <li><a  href="main.jsp?page=day0405/multi_column_row">컬럼여러개에 레코드  여러개</a></li>
                <li><a  href="main.jsp?page=day0405/multi_param">where절의 값이  여러개</a></li>
                <li><a  href="main.jsp?page=day0405/lessthan">&lt; 의 비교</a></li>
                <li><a  href="main.jsp?page=day0405/greaterthan">&gt; 의 비교</a></li>
                <li><a  href="main.jsp?page=day0405/like">like</a></li>
              </ul>
            </li>
          </ul>
        </li>
        </ul>
     </nav>
//MyBatisDAO1.java
package kr.co.sist.exam.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.co.sist.exam.domain.Emp;
import kr.co.sist.exam.domain.Zipcode;
import kr.co.sist.exam.vo.EmpVO;
public class MyBatisDAO1 {
     public List<Emp> multiParam(EmpVO ev){
           List<Emp> list=null;
           //4.Handler얻기
           SqlSession  ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
           
           list=ss.selectList("multiParam",ev);
           
           ss.close();
           
           return list;
     }//multiParam
     
     public List<Emp> lessThan(int sal){
           List<Emp> list=null;
           
           //4.
           SqlSession  ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
           list=ss.selectList("lessThan",sal);
           ss.close();
           
           return list;
     }//lessThan
     
     public List<Emp> greaterThan(int sal){
           List<Emp> list=null;
           
           //4.
           SqlSession  ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
           list=ss.selectList("greaterThan",sal);
           ss.close();
           
           return list;
     }//greaterThan
     
     public List<Zipcode> like(String dong){
           List<Zipcode> list=null;
           
           //4.
           SqlSession  ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
           list=ss.selectList("like",dong);
           ss.close();
           
           return list;
     }//like
     
     public static void main(String[] args) {
           MyBatisDAO1 md=new MyBatisDAO1();
           //md.multiParam(new EmpVO(30, "SALESMAN"));
           //md.lessThan(3000);
           //md.greaterThan(3000);
           md.like("상도동");
     }//main
}//class
//MyBatisService.java
package kr.co.sist.exam.service;
import java.util.List;
import kr.co.sist.exam.dao.MyBatisDAO1;
import kr.co.sist.exam.domain.Emp;
import kr.co.sist.exam.domain.Zipcode;
import kr.co.sist.exam.vo.EmpVO;
public class MyBatisService1 {
     public List<Emp> multiParam(EmpVO ev){
           List<Emp> list=null;
           MyBatisDAO1 mb_dao1=new MyBatisDAO1();
           
           list=mb_dao1.multiParam(ev);
           
           return list;
     }//multiParam
     
     public List<Emp> lessThan(int sal){
           List<Emp> list=null;
           
           if(sal<0) {
                sal=-sal;
           }//end if
           
           MyBatisDAO1 md_dao1=new MyBatisDAO1();
           list=md_dao1.lessThan(sal);
           
           return list;
     }//lessThan
     
     public List<Emp> greaterThan(int sal){
           List<Emp> list=null;
           
           if(sal > 10000) {
                sal=10000;
           }//end if
           
           MyBatisDAO1 md_dao1=new MyBatisDAO1();
           list=md_dao1.greaterThan(sal);
           
           return list;
     }//greaterThan
     
     public List<Zipcode> like(String dong){
           List<Zipcode> list=null;
           
           MyBatisDAO1 md_dao1=new MyBatisDAO1();
           list=md_dao1.like(dong);
           
           return list;
     }//like
}
//like.jsp
<%@page import="kr.co.sist.exam.domain.Zipcode"%>
<%@page import="kr.co.sist.exam.service.MyBatisService1"%>
<%@page import="kr.co.sist.exam.domain.Emp"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.dao.MyBatisDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<%
     MyBatisService1 mbs=new MyBatisService1();
     
     String dong=request.getParameter("dong");
     
     if(dong!=null){
           List<Zipcode> list=mbs.like(dong);
           pageContext.setAttribute("zipList", list);
     }//end if
%>
<form name="frm" action="main.jsp">
<input type="hidden" name="page" value="day0405/like"/>
<label>동</label>
<input type="text" name="dong" class="inputBox"/>
<input type="submit" value="조회", class="btn"/><br/>
예) 상도동, 역삼동
</form>
<div>
<c:if test="${not empty param.dong}">
     <div>
           ${param.dong} 의 조회
     </div>
     <table border="1">
           <tr>
                <th width="80">우편번호</th>
                <th width="400">주소</th>
           </tr>
           <c:if test="${empty zipList}">
           <tr>
                <td colspan="7" align="center">
                     <strong>${param.dong}</strong> 은 존재하지  않습니다.
                </td>
           </tr>
           </c:if>
           <c:forEach var="zip" items="${zipList}">
           <tr>
                <td><c:out value="${zip.zipcode}"/></td>
                <td><c:out value="${zip.sido} ${zip.gugun}  ${zip.dong} ${zip.bunji}"/></td>
           </tr>
           </c:forEach>
     </table>
</c:if>
<script type="text/javascript"  src="//dapi.kakao.com/v2/maps/sdk.js?appkey=acbead349136da6f3bb665febdb9861f&libraries=services"></script>
<script type="text/javascript">
$(function(){
/* var container = document.getElementById('map'); //지도를 담을  영역의 DOM 레퍼런스
var options = { //지도를 생성할 때 필요한 기본 옵션
     center: new daum.maps.LatLng(37.499448, 127.033151),  //지도의 중심좌표.
     level: 3 //지도의 레벨(확대, 축소 정도)
};
var map = new daum.maps.Map(container, options); //지도 생성 및  객체 리턴 */
     var mapContainer = document.getElementById('map'), //  지도를 표시할 div
    mapOption = {
        center: new daum.maps.LatLng(33.450701, 126.570667), //  지도의 중심좌표
        level: 3 // 지도의 확대 레벨
    };  
// 지도를 생성합니다    
var map = new daum.maps.Map(mapContainer, mapOption);
// 주소-좌표 변환 객체를 생성합니다
var geocoder = new daum.maps.services.Geocoder();
// 주소로 좌표를 검색합니다
geocoder.addressSearch('서울특별시 강남구 역삼동 테헤란로 132',  function(result, status) {
    // 정상적으로 검색이 완료됐으면
     if (status === daum.maps.services.Status.OK) {
        var coords = new daum.maps.LatLng(result[0].y,  result[0].x);
        // 결과값으로 받은 위치를 마커로 표시합니다
        var marker = new daum.maps.Marker({
            map: map,
            position: coords
        });
        // 인포윈도우로 장소에 대한 설명을 표시합니다
        var infowindow = new daum.maps.InfoWindow({
            content: '<div  style="width:150px;text-align:center;padding:6px  0;">쌍용교욱센터</div>'
        });
        infowindow.open(map, marker);
        // 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
        map.setCenter(coords);
    }
});    
});//만약 javaScript가 없다면 onload로 넣어준다.
</script>
<div id="map" style="width:500px;height:400px;"></div>
</div>













<<끝난 부분>>>
//EmpVO.java
package kr.co.sist.exam.vo;
public class EmpVO {
     private int deptno;
     private String job;
     
     public EmpVO(int deptno, String job) { //객체화를 내가해  인자있는생성자 필요
           this.deptno = deptno;
           this.job = job;
     }
     public int getDeptno() {
           return deptno;
     }
     public void setDeptno(int deptno) {
           this.deptno = deptno;
     }
     public String getJob() {
           return job;
     }
     public void setJob(String job) {
           this.job = job;
     }
}
//multi_param.jsp
<%@page import="kr.co.sist.exam.service.MyBatisService1"%>
<%@page import="kr.co.sist.exam.vo.EmpVO"%>
<%@page import="kr.co.sist.exam.domain.Emp"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.service.MyBatisService"%>
<%@page import="kr.co.sist.exam.dao.MyBatisDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<%
/*   MyBatisService mbs=new MyBatisService();
     List<Integer> deptnoList=mbs.multiRow();
     pageContext.setAttribute("deptnoList", deptnoList);
     
     String deptno=request.getParameter("deptno");
     
     if(deptno!=null){
           List<Emp>  list=mbs.multiColumnRow(Integer.parseInt(deptno));
           pageContext.setAttribute("empList", list);
     }//end if */
%>
<%
     String deptno=request.getParameter("deptno");
     
     if(deptno!=null){
           MyBatisService1 mbs=new MyBatisService1();
           String job=request.getParameter("job");
           EmpVO ev=new EmpVO(Integer.parseInt(deptno),job);
           List<Emp> list=mbs.multiParam(ev);
           pageContext.setAttribute("empList", list);
     }//end if
%>
<form name="frm" action="main.jsp">
<input type="hidden" name="page" value="day0405/multi_param"/>
<label>부서번호</label>
<c:set var="deptno" value="10,20,30,40"/>
<c:forTokens items="${deptno}" delims="," var="deptno">
<input type="radio" name="deptno" value="${deptno}"  ${param.deptno eq deptno?"checked='checked'":'' } />
<c:out value="${deptno}" escapeXml="false"/>
</c:forTokens><br/>
<label>직무</label>
<c:set var="job"  value="ANALYST,CLERK,MANAGER,SALESMAN,PRESIDENT"/>
<c:forTokens items="${job}" delims="," var="job">
<input type="radio" name="job" value="${job}" ${param.job eq  job?"checked='checked'":'' }/>
<c:out value="${job}" escapeXml="false"/>
</c:forTokens><br/>
<input type="submit" value="부서별 사원 조회", class="btn"/>
</form>
<div>
<c:if test="${not empty param.deptno}">
     <table border="1">
           <tr>
                <th width="40">번호</th>
                <th width="80">사원번호</th>
                <th width="120">사원명</th>
                <th width="80">매니저번호</th>
                <th width="80">연봉</th>
                <th width="150">입사일</th>
                <th width="100">직무</th>
           </tr>
           <c:if test="${empty empList}">
           <tr>
                <td colspan="7" align="center">
                <strong>${param.deptno}</strong>번 부서에는  사원이 존재하지 않습니다.
                </td>
           </tr>
           </c:if>
           <c:forEach var="emp" items="${empList}">
           <c:set var="i" value="${i+1}"/>
           <tr>
                <td><c:out value="${i}"/></td>
                <td><c:out value="${emp.empno}"/></td>
                <td><c:out value="${emp.ename}"/></td>
                <td><c:out value="${emp.mgr}"/></td>
                <td><c:out value="${emp.sal}"/></td>
                <td><c:out value="${emp.hiredate}"/></td>
                <td><c:out value="${emp.job}"/></td>
           </tr>
           </c:forEach>
     </table>
</c:if>
</div>
//Emp.java
package kr.co.sist.exam.domain;
public class Emp {
     private int empno,sal,mgr;
     private String  ename,job,hiredate;
     
     public int getEmpno() {
           return empno;
     }
     public void setEmpno(int empno) {
           this.empno = empno;
     }
     public int getSal() {
           return sal;
     }
     public void setSal(int sal) {
           this.sal = sal;
     }
     public int getMgr() {
           return mgr;
     }
     public void setMgr(int mgr) {
           this.mgr = mgr;
     }
     public String getEname() {
           return ename;
     }
     public void setEname(String ename) {
           this.ename = ename;
     }
     public String getJob() {
           return job;
     }
     public void setJob(String job) {
           this.job = job;
     }
     public String getHiredate() {
           return hiredate;
     }
     public void setHiredate(String hiredate) {
           this.hiredate = hiredate;
     }
     
}//class
//multi_column_row.jsp
<%@page import="kr.co.sist.exam.domain.Emp"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.service.MyBatisService"%>
<%@page import="kr.co.sist.exam.dao.MyBatisDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<%
     MyBatisService mbs=new MyBatisService();
     List<Integer> deptnoList=mbs.multiRow();
     pageContext.setAttribute("deptnoList", deptnoList);
     
     String deptno=request.getParameter("deptno");
     
     if(deptno!=null){
           List<Emp>  list=mbs.multiColumnRow(Integer.parseInt(deptno));
           pageContext.setAttribute("empList", list);
     }//end if
%>
<form name="frm" action="main.jsp">
<input type="hidden" name="page"  value="day0405/multi_column_row"/>
<label>부서번호</label>
<select name="deptno">
<c:forEach var="deptno" items="${deptnoList}">
     <option value="${deptno}"><c:out value="${deptno}"  escapeXml="false"></c:out>
</c:forEach>
</select>
<input type="submit" value="부서별 사원 조회", class="btn"/>
</form>
<div>
<c:if test="${not empty param.deptno}">
     <table border="1">
           <tr>
                <th width="40">번호</th>
                <th width="80">사원번호</th>
                <th width="120">사원명</th>
                <th width="80">매니저번호</th>
                <th width="80">연봉</th>
                <th width="150">입사일</th>
                <th width="100">직무</th>
           </tr>
           <c:if test="${empty empList}">
           <tr>
                <td colspan="7" align="center">
                <strong>${param.deptno}</strong>번 부서에는  사원이 존재하지 않습니다.
                </td>
           </tr>
           </c:if>
           <c:forEach var="emp" items="${empList}">
           <c:set var="i" value="${i+1}"/>
           <tr>
                <td><c:out value="${i}"/></td>
                <td><c:out value="${emp.empno}"/></td>
                <td><c:out value="${emp.ename}"/></td>
                <td><c:out value="${emp.mgr}"/></td>
                <td><c:out value="${emp.sal}"/></td>
                <td><c:out value="${emp.hiredate}"/></td>
                <td><c:out value="${emp.job}"/></td>
           </tr>
           </c:forEach>
     </table>
</c:if>
</div>
//MyBatisService.java
package kr.co.sist.exam.service;

import java.util.List;

import kr.co.sist.exam.dao.MyBatisDAO;
import kr.co.sist.exam.domain.DeptInfo;
import kr.co.sist.exam.domain.Emp;

public class MyBatisService {
    
    /**
     * 컬럼하나 레코드하나
     * @return
     */
    public String deptName() {
        MyBatisDAO mb_dao=MyBatisDAO.getInstance();
        String dname=mb_dao.singleColumn()+"부서";
        return dname;
    }//deptName -controller가 가져다 사용하게 된다.
    
    /**
     * 컬럼여러개 레코드하나
     * @return
     */
    public DeptInfo deptInfo() {
        MyBatisDAO mb_dao=MyBatisDAO.getInstance();
        DeptInfo di=mb_dao.multiColumn();
        return di;
    }//deptInfo
    
    public List<Integer> multiRow(){
        List<Integer> list=null;
        MyBatisDAO mb_dao=MyBatisDAO.getInstance();
        list=mb_dao.multiRow();
        
        return list;
    }//multiRow
    
    public List<Emp> multiColumnRow(int deptno){
        List<Emp> list=null;
        
        MyBatisDAO mb_dao=MyBatisDAO.getInstance();
        
        list=mb_dao.multiColumnRow(deptno);
        
        return list;
    }//multiColumnRow
}//class
//MyBatisDAO.java
package kr.co.sist.exam.dao;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

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 kr.co.sist.exam.domain.DeptInfo;
import kr.co.sist.exam.domain.Emp;

public class MyBatisDAO {
    
    private static MyBatisDAO mb_dao;
    private SqlSessionFactory ssf=null;
    
    private MyBatisDAO() {
        
    }//MyBatisDAO
    
    public static MyBatisDAO getInstance() {
        if(mb_dao==null) {
            mb_dao=new MyBatisDAO();
        }//end if
        return mb_dao;
    }//getInstance
    
    public synchronized SqlSessionFactory getSessionFactory() {
        if(ssf==null) {
            org.apache.ibatis.logging.LogFactory.useLog4JLogging();
            
            Reader reader=null;
            try {
                //1.설정용 xml 로딩
                reader=Resources.getResourceAsReader("kr/co/sist/exam/dao/mybatis_config.xml");
                //2.MyBatis Framework 생성
                SqlSessionFactoryBuilder ssfb=new SqlSessionFactoryBuilder();
                //3.DB와 연동된 객체 받기
                ssf=ssfb.build(reader);
                if(reader!=null) {reader.close();}//end if
                
            } catch (IOException e) {
                e.printStackTrace();
            }//end catch
        }//end if
        return ssf;
    }//getSessionFactory
    
    public String singleColumn() {
        //MyBatis Handler를 얻어 사용하여 Mapper(xml)에 있는 ID에 찾고 Parsing하여 조회된 결과를 얻는다.
        String dname="";
        SqlSession ss=getSessionFactory().openSession();
        
        dname=ss.selectOne("singleColumn");
        ss.close();
        return dname;
    }//singleColumn
    
    public DeptInfo multiColumn() {
        DeptInfo di=null;
        
        MyBatisDAO mb_dao=MyBatisDAO.mb_dao;
        SqlSession ss=mb_dao.getSessionFactory().openSession();
        
        di=ss.selectOne("multiColumn");
        ss.close();
        
        return di;
    }//multiColumn
    
    public List<Integer> multiRow(){
        List<Integer> list=null;
        
        SqlSession ss=getInstance().getSessionFactory().openSession();
        list=ss.selectList("multiRow");
        ss.close();
        
        return list;
    }//multiRow
    
    public List<Emp> multiColumnRow(int deptno){
        List<Emp> list=null;
        //4.Handler 얻기 =>얻은후에는 종료로 메모리 누수를 방지해 주어야 한다.
        SqlSession ss=getSessionFactory().openSession();

        //5.mapper에서 쿼리가 존재하는 id를 찾아 Parsing하여 실행
        list=ss.selectList("multiColumnRow",deptno);
        ss.close();
        return list;
    }//multiColumnRow
    
    public static void main(String[] args) {
        MyBatisDAO m=MyBatisDAO.getInstance();
        //System.out.println(m.getSessionFactory());
        //System.out.println(m.singleColumn());
        //System.out.println(m.multiColumn());
        System.out.println(m.multiColumnRow(20));
    }//main    
}//class
//lessthan.jsp
<%@page import="kr.co.sist.exam.service.MyBatisService1"%>
<%@page import="kr.co.sist.exam.domain.Emp"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.dao.MyBatisDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<%
     MyBatisService1 mbs=new MyBatisService1();
     
     String sal=request.getParameter("sal");
     
     if(sal!=null){
           List<Emp> list=mbs.lessThan(Integer.parseInt(sal));
           pageContext.setAttribute("empList", list);
     }//end if
%>
<form name="frm" action="main.jsp">
<input type="hidden" name="page" value="day0405/lessthan"/>
<label>연봉</label>
<input type="text" name="sal" class="inputBox"/>
<input type="submit" value="사원 조회", class="btn"/>
</form>
<div>
<c:if test="${not empty param.sal}">
     <div>
           ${param.sal} 보다 연봉을 적게 받는 사원 정보
     </div>
     <table border="1">
           <tr>
                <th width="40">번호</th>
                <th width="80">사원번호</th>
                <th width="120">사원명</th>
                <th width="80">매니저번호</th>
                <th width="80">연봉</th>
                <th width="150">입사일</th>
                <th width="100">직무</th>
           </tr>
           <c:if test="${empty empList}">
           <tr>
                <td colspan="7" align="center">
                <strong>${param.sal}</strong>보다 적게 받는  사원은 존재하지 않습니다.
                </td>
           </tr>
           </c:if>
           <c:forEach var="emp" items="${empList}">
           <c:set var="i" value="${i+1}"/>
           <tr>
                <td><c:out value="${i}"/></td>
                <td><c:out value="${emp.empno}"/></td>
                <td><c:out value="${emp.ename}"/></td>
                <td><c:out value="${emp.mgr}"/></td>
                <td><c:out value="${emp.sal}"/></td>
                <td><c:out value="${emp.hiredate}"/></td>
                <td><c:out value="${emp.job}"/></td>
           </tr>
           </c:forEach>
     </table>
</c:if>
</div>
//Zipcode.java
package kr.co.sist.exam.domain;
public class Zipcode {
     private String zipcode,sido,gugun,dong,bunji;
     public String getZipcode() {
           return zipcode;
     }
     public void setZipcode(String zipcode) {
           this.zipcode = zipcode;
     }
     public String getSido() {
           return sido;
     }
     public void setSido(String sido) {
           this.sido = sido;
     }
     public String getGugun() {
           return gugun;
     }
     public void setGugun(String gugun) {
           this.gugun = gugun;
     }
     public String getDong() {
           return dong;
     }
     public void setDong(String dong) {
           this.dong = dong;
     }
     public String getBunji() {
           return bunji;
     }
     public void setBunji(String bunji) {
           this.bunji = bunji;
     }
     
}
//greaterthan.jsp
<%@page import="kr.co.sist.exam.service.MyBatisService1"%>
<%@page import="kr.co.sist.exam.domain.Emp"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.dao.MyBatisDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<%
     MyBatisService1 mbs=new MyBatisService1();
     
     String sal=request.getParameter("sal");
     
     if(sal!=null){
           List<Emp>  list=mbs.greaterThan(Integer.parseInt(sal));
           pageContext.setAttribute("empList", list);
     }//end if
%>
<form name="frm" action="main.jsp">
<input type="hidden" name="page" value="day0405/greaterthan"/>
<label>연봉</label>
<input type="text" name="sal" class="inputBox"/>
<input type="submit" value="사원 조회", class="btn"/>
</form>
<div>
<c:if test="${not empty param.sal}">
     <div>
           ${param.sal} 보다 연봉을 많이 받는 사원 정보
     </div>
     <table border="1">
           <tr>
                <th width="40">번호</th>
                <th width="80">사원번호</th>
                <th width="120">사원명</th>
                <th width="80">매니저번호</th>
                <th width="80">연봉</th>
                <th width="150">입사일</th>
                <th width="100">직무</th>
           </tr>
           <c:if test="${empty empList}">
           <tr>
                <td colspan="7" align="center">
                <strong>${param.sal}</strong>보다 많이 받는  사원은 존재하지 않습니다.
                </td>
           </tr>
           </c:if>
           <c:forEach var="emp" items="${empList}">
           <c:set var="i" value="${i+1}"/>
           <tr>
                <td><c:out value="${i}"/></td>
                <td><c:out value="${emp.empno}"/></td>
                <td><c:out value="${emp.ename}"/></td>
                <td><c:out value="${emp.mgr}"/></td>
                <td><c:out value="${emp.sal}"/></td>
                <td><c:out value="${emp.hiredate}"/></td>
                <td><c:out value="${emp.job}"/></td>
           </tr>
           </c:forEach>
     </table>
</c:if>
</div>


 

반응형