반응형
//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><a href="#void" onclick="setMarker('${zip.sido} ${zip.gugun} ${zip.dong}','${zip.dong}')"><c:out value="${zip.zipcode}"/></a></td>
<td><a href="#void" onclick="setMarker('${zip.sido} ${zip.gugun} ${zip.dong}','${zip.dong}')"><c:out value="${zip.sido} ${zip.gugun} ${zip.dong} ${zip.bunji}"/></a></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">
var mapContainer=null;
var mapOption=null;
$(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); //지도 생성 및 객체 리턴 */
mapContainer = document.getElementById('map'), // 지도를 표시할 div
mapOption = {
center: new daum.maps.LatLng(33.450701, 126.570667), // 지도의 중심좌표
level: 3 // 지도의 확대 레벨
};
setMarker("서울시 동작구 상도동","살기좋은 상도동");
});//만약 javaScript가 없다면 onload로 넣어준다.
function setMarker(addr,dong){
// 지도를 생성합니다
var map = new daum.maps.Map(mapContainer, mapOption);
// 주소-좌표 변환 객체를 생성합니다
var geocoder = new daum.maps.services.Geocoder();
// 주소로 좌표를 검색합니다
geocoder.addressSearch(addr, 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;">'+dong+'</div>'
});
infowindow.open(map, marker);
// 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
map.setCenter(coords);
}//end if
});
}//setMaker
</script>
<div id="map" style="width:500px;height:400px;"></div>
</div>
//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>
<!-- < 의 조회
사원테이블에서 입력된 연봉보다 적게 받는 사원의 사원번호, 사원명,직무,매니저번호,입사일을 조회하세요
'<'는 직접 사용할 수 없다. <로 사용.
'<'를 직접 사용하고 싶다면 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>
<!-- > 의 조회
사원테이블에서 입력된 연봉보다 많이 받는 사원의 사원번호, 사원명,직무,매니저번호,입사일을 조회하세요
바로 사용해도 에러는 나지 않지만 권장하는 방법은 아니다.
>는 에러가 발생하지 않는다. > <![CDATA[>]]> 다 가능!
직관성이 떨어지는게 단점
-->
<select id="greaterThan" resultMap="empResult" parameterType="Integer">
<include refid="empDup"/>
where sal > #{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>
</mapper>
//DiaryList.java Domain
package kr.co.sist.exam.domain;
public class DiaryList {
private int num;
private String subject,writer, evt_date,w_date;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getEvt_date() {
return evt_date;
}
public void setEvt_date(String evt_date) {
this.evt_date = evt_date;
}
public String getW_date() {
return w_date;
}
public void setW_date(String w_date) {
this.w_date = w_date;
}
}
//DiaryListParamVO
package kr.co.sist.exam.vo;
public class DiaryListParamVO {
private int startNum,endNum;
public DiaryListParamVO(int startNum, int endNum) {
this.startNum = startNum;
this.endNum = endNum;
}
public int getStartNum() {
return startNum;
}
public void setStartNum(int startNum) {
this.startNum = startNum;
}
public int getEndNum() {
return endNum;
}
public void setEndNum(int endNum) {
this.endNum = endNum;
}
}//class
//subquery.jsp
<%@page import="kr.co.sist.exam.domain.DiaryList"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.vo.DiaryListParamVO"%>
<%@page import="kr.co.sist.exam.service.MyBatisService1"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String currentPage=request.getParameter("currentPage");
MyBatisService1 mbs1=new MyBatisService1();
int totalCount=mbs1.totalCount();
int pageScale=mbs1.pageScale();
int totalPage=mbs1.totalPage(totalCount, pageScale);
int startNum=mbs1.startNum(currentPage, pageScale);
int endNum=mbs1.endNum(startNum, pageScale);
DiaryListParamVO dlp_vo=new DiaryListParamVO(startNum,endNum);
List<DiaryList> list=mbs1.diaryList(dlp_vo);
pageContext.setAttribute("diaryList", list);
%>
<table style="border:1px solid #333">
<tr>
<th width="80">번호</th>
<th width="300">제목</th>
<th width="120">작성자</th>
<th width="150">이벤트 일자</th>
<th width="150">작성일</th>
</tr>
<c:if test="${empty diaryList}">
<tr>
<td colspan="5">작성된 글이 없습니다.</td>
</tr>
</c:if>
<c:forEach var="dl" items="${diaryList}">
<c:set var="i" value="${i+1}"/>
<tr>
<td><c:out value="${i}"/></td>
<td><c:out value="${dl.subject}"/></td>
<td><c:out value="${dl.writer}"/></td>
<td><c:out value="${dl.evt_date}"/></td>
<td><c:out value="${dl.w_date}"/></td>
</tr>
</c:forEach>
</table>
<%-- <%= totalCount+"/"+pageScale+"/"+totalPage+"/"+startNum+"/"+endNum %> --%>
//Union.java
package kr.co.sist.exam.domain;
public class Union {
private int empno,sal,deptno;
private String ename,job,hiredate,retired;
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 getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
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;
}
public String getRetired() {
return retired;
}
public void setRetired(String retired) {
this.retired = retired;
}
}
//union.jsp
<%@page import="kr.co.sist.exam.domain.Union"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.service.MyBatisService1"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
MyBatisService1 mbs1=new MyBatisService1();
List<Union> list=mbs1.union();
pageContext.setAttribute("list", list);
%>
<table border="1" >
<tr>
<th width="60">사원번호</th>
<th width="120">사원명</th>
<th width="120">직무</th>
<th width="80">연봉</th>
<th width="150">입사일</th>
<th width="60">부서번호</th>
<th width="60">퇴사여부</th>
</tr>
<c:if test="${empty list}">
<tr>
<td colspan="7" align="center">사원이 존재하지 않습니다.</td>
</tr>
</c:if>
<c:forEach var="emp" items="${list}">
<tr>
<td><c:out value="${emp.empno}"/></td>
<td><c:out value="${emp.ename}"/></td>
<td><c:out value="${emp.job}"/></td>
<td><c:out value="${emp.sal}"/></td>
<td><c:out value="${emp.hiredate}"/></td>
<td><c:out value="${emp.deptno}"/></td>
<td><c:out value="${emp.retired eq 'N'?'재직자':'퇴사자'}"/></td>
</tr>
</c:forEach>
</table>
//Union query
create table union_test as
(select empno,ename,job,sal,hiredate,deptno from emp);
alter table union_test add retired char(1);
select * from Union_test;
update union_test
set retired ='Y'
where to_char(hiredate,'yyyymm') between '198102' and '198110';
update union_test
set retired ='N'
where not( to_char(hiredate,'yyyymm') between '198102' and '198110');
commit;
select empno,ename,job,sal,hiredate,deptno,retired
from union_test
where retired='N'
union all
select empno,ename,job,sal,hiredate,deptno,retired
from union_test
where retired='Y'
//config는 설정??
////exam_mapper2.xml(SQL)=>domain/vo=> MyBatisDAO1.java(단위테스트)=>Service1=>main_menu.jsp에 추가해주고=>jsp를 만들어 준다.
<<<이렇게 한세트>>
//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© 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">< 의 비교</a></li>
<li><a href="main.jsp?page=day0405/greaterthan">> 의 비교</a></li>
<li><a href="main.jsp?page=day0405/like">like</a></li>
</ul>
</li>
<li><a href="#void">3일차</a>
<ul>
<li><a href="main.jsp?page=day0408/subquery">subquery</a></li>
<li><a href="main.jsp?page=day0408/union">union</a></li>
<li><a href="main.jsp?page=day0408/join">join</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.DiaryList;
import kr.co.sist.exam.domain.Emp;
import kr.co.sist.exam.domain.EmpJoin;
import kr.co.sist.exam.domain.Union;
import kr.co.sist.exam.domain.Zipcode;
import kr.co.sist.exam.vo.DiaryListParamVO;
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 int diaryTotalCount() {
int cnt=0;
SqlSession ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
cnt=ss.selectOne("diaryCnt");
return cnt;
}//diaryTotalCount
public List<DiaryList> subquery(DiaryListParamVO dlpvo){
List<DiaryList> list=null;
SqlSession ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
list=ss.selectList("subquery",dlpvo);
return list;
}//subquery
public List<Union> union(){
List<Union> list=null;
SqlSession ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
list=ss.selectList("union");
return list;
}//union
public List<EmpJoin> join(int mgr){
List<EmpJoin> list=null;
SqlSession ss=MyBatisDAO.getInstance().getSessionFactory().openSession();
list=ss.selectList("join",mgr);
return list;
}//join
public static void main(String[] args) {
MyBatisDAO1 md=new MyBatisDAO1();
//md.multiParam(new EmpVO(30, "SALESMAN"));
//md.lessThan(3000);
//md.greaterThan(3000);
//md.like("상도동");
//md.diaryTotalCount();
//md.union();
md.join(7698);
}//main
}//class
//MyBatisService1.java
package kr.co.sist.exam.service;
import java.util.List;
import kr.co.sist.exam.dao.MyBatisDAO1;
import kr.co.sist.exam.domain.DiaryList;
import kr.co.sist.exam.domain.Emp;
import kr.co.sist.exam.domain.EmpJoin;
import kr.co.sist.exam.domain.Union;
import kr.co.sist.exam.domain.Zipcode;
import kr.co.sist.exam.vo.DiaryListParamVO;
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
////////////////////게시판의 리스트를 얻어오자//////////////////////////////////////
//게시판의 총 갯수
public int totalCount() {
int cnt=0;
MyBatisDAO1 mb_dao=new MyBatisDAO1();
cnt=mb_dao.diaryTotalCount();
return cnt;
}//totalCount
//한화면에 보여줄 게시물의 갯수
public int pageScale() {
return 10;
}//pageScale
//총 페이지 수
public int totalPage(int totalCount, int pageScale) {
int totalPage=0;
totalPage=(int)Math.ceil((double)totalCount/pageScale);
return totalPage;
}//totalPage
//시작번호
public int startNum(String currentPage, int pageScale) {
int startNum=1;
if(currentPage !=null) {
int tempPage=Integer.parseInt(currentPage);
startNum =tempPage*pageScale-pageScale+1;
}//end if
return startNum;
}//startNum
//끝번호
public int endNum(int startNum, int pageScale) {
return startNum+pageScale-1;
}//endNum
public List<DiaryList> diaryList(DiaryListParamVO dlp_vo){
List<DiaryList> list=null;
MyBatisDAO1 mb_dao=new MyBatisDAO1();
list=mb_dao.subquery(dlp_vo);
return list;
}//diaryList
public List<Union> union(){
List<Union> list=null;
MyBatisDAO1 mb_dao=new MyBatisDAO1();
list=mb_dao.union();
return list;
}//union
public List<EmpJoin> join(int mgr){
List<EmpJoin> list=null;
MyBatisDAO1 mb_dao=new MyBatisDAO1();
list=mb_dao.join(mgr);
return list;
}//join
}//class
//exam_mapper2.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">
<mapper namespace="kr.co.sist.exam2">
<!-- Diary List에 대한 Mapper 설정 -->
<resultMap type="kr.co.sist.exam.domain.DiaryList" id="dlResult">
<result column="num" property="num"/>
<result column="subject" property="subject"/>
<result column="writer" property="writer"/>
<result column="evt_date" property="evt_date"/>
<result column="w_date" property="w_date"/>
</resultMap>
<!-- Union에서 사용되는 resultMap -->
<resultMap type="kr.co.sist.exam.domain.Union" id="unionResult">
<result column="empno" property="empno"/>
<result column="sal" property="sal"/>
<result column="deptno" property="deptno"/>
<result column="ename" property="ename"/>
<result column="job" property="job"/>
<result column="hiredate" property="hiredate"/>
<result column="retired" property="retired"/>
</resultMap>
<!-- Join resultMap -->
<resultMap type="kr.co.sist.exam.domain.EmpJoin" id="empResult">
<result column="empno" property="empno"/>
<result column="ename" property="ename"/>
<result column="sal" property="sal"/>
<result column="hiredate" property="hiredate"/>
<result column="deptno" property="deptno"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
</resultMap>
<select id="diaryCnt" resultType="int">
select count(*) cnt from diary
</select>
<!-- subquery의 조회
diary 테이블에서 가장 마지막 글에서 부터 시작번호와 끝번호 사이의 글을 조회
-->
<select id="subquery" resultMap="dlResult" parameterType="kr.co.sist.exam.vo.DiaryListParamVO">
select r_num,num,subject,writer, e_year||'-'||e_month||'-'||e_day evt_date,
to_char(w_date,'yyyy-mm-dd hh24:mi') w_date
from (select num,subject,writer,e_year,e_month,e_day, w_date, row_number() over(order by w_date desc) r_num
from diary)
where r_num between #{startNum} and #{endNum}
</select>
<!-- union의 조회 : 퇴사한 사원과 재직중인 사원을 구분하여 조회-->
<select id="union" resultMap="unionResult" >
select empno,ename,job,sal,to_char(hiredate,'yyyy-mm-dd') hiredate,deptno,retired
from union_test
where retired='N'
union all
select empno,ename,job,sal,to_char(hiredate,'yyyy-mm-dd') hiredate,deptno,retired
from union_test
where retired='Y'
</select>
<!-- join의 조회 : 매니저 번호를 입력받아 매니저가 관리하는 사원들의 사원번호,사원명,연봉,입사일,부서번호,부서명,위치를 조회 -->
<select id="join" resultMap="empResult" parameterType="Integer">
select e.empno,e.ename,e.sal,e.hiredate,d.deptno,d.dname,d.loc
from emp e, dept d
where e.deptno=d.deptno and e.mgr=#{mgr}
</select>
<!-- join+subquery 의 조회 -->
<!-- 컬럼명 또는 테이블명이 동적일 때의 조회 -->
<!-- dynamic query : where,if,choose,foreach -->
<!-- procedure 호출 -->
</mapper>
//EmpJoin.java
package kr.co.sist.exam.domain;
public class EmpJoin {
private int empno,sal,deptno;
private String ename,hiredate,dname,loc;
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 getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getHiredate() {
return hiredate;
}
public void setHiredate(String hiredate) {
this.hiredate = hiredate;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
//join.jsp
<%@page import="kr.co.sist.exam.domain.EmpJoin"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.sist.exam.service.MyBatisService1"%>
<%@page import="kr.co.sist.exam.dao.MyBatisDAO1"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String mgr=request.getParameter("mgr");
if(mgr !=null){
MyBatisService1 mbs1=new MyBatisService1();
List<EmpJoin> list=mbs1.join(Integer.parseInt(mgr));
pageContext.setAttribute("empList", list);
}//end if
%>
<div>
<c:set var="mgr" value="7566,7698,7788,7839,7902"/>
<c:forTokens var="mgr" items="${mgr}" delims=",">
[<a href="main.jsp?page=day0408/join&mgr=${mgr}"><c:out value="${mgr}"/></a>]
</c:forTokens>
</div>
<div>
<table border="1">
<tr>
<th width="60">사원번호</th>
<th width="100">사원명</th>
<th width="80">연봉</th>
<th width="150">입사일</th>
<th width="60">부서번호</th>
<th width="100">부서명</th>
<th width="80">위치</th>
</tr>
<c:if test="${empty empList}">
<tr>
<td colspan="7" align="center">
${param.mgr} 매니저가 관리하는 사원은 존재하지 않습니다.
</td>
</tr>
</c:if>
<c:forEach var="emp" items="${empList}">
<tr>
<td><c:out value="${emp.empno}"/></td>
<td><c:out value="${emp.ename}"/></td>
<td><c:out value="${emp.sal}"/></td>
<td><c:out value="${emp.hiredate}"/></td>
<td><c:out value="${emp.deptno}"/></td>
<td><c:out value="${emp.dname}"/></td>
<td><c:out value="${emp.loc}"/></td>
</tr>
</c:forEach>
</table>
</div>
반응형
'국비지원학원 > MyBatis' 카테고리의 다른 글
115일차-페이지 선택유지/dynamicQuery/procedure사용 (0) | 2019.04.19 |
---|---|
114일차-Dynamic Query조회 (0) | 2019.04.19 |
112일차-MyBatis (0) | 2019.04.17 |
111일차-MyBatis (0) | 2019.04.17 |
110일차-Framework_MyBatis (0) | 2019.04.15 |