프로그래밍에서 특정 운영 체제를 위한 응용 프로그램 표준 구조를 구현하는 클래스와 라이브러리 모임
개발 기간 단축
성능향상
유지보수성 향상
프레임워크 학습 필요
프레임워크 선택 어려움
유연성 부족
https://blog.mybatis.org 참고 / 들어가서 다운로드
마이바티스는 개발자가 지정한 SQL, 저장프로시저 그리고 몇가지 고급 매핑을 지원하는 퍼시스턴스 프레임워크이다.
마이바티스는 JDBC로 처리하는 상당부분의 코드와 파라미터 설정및 결과 매핑을 대신해준다.
마이바티스는 데이터베이스 레코드에 원시타입과 Map 인터페이스 그리고 자바 POJO 를 설정해서 매핑하기 위해 XML과 애노테이션을 사용할 수 있다.
Mybatis로 프로젝트 만드려면 3가지 드라이버 필요
MyBatis
lib
jdbc 드라이버
mybatis 프레임워크
로그출력
작업 진행에대한 로그를 출력하는 프레임워크
설정파일 2가지 필요
설정파일
데이터베이스 접속
SQL mapper
Dynamic Web Project => Maven(Gradle) Project
java-wordspace로 이클립스 접속
DEBUG : debug을 위한 용도로, 일반 정보를 상세하게 출력
=> 개발시 디버그 용도로 사용한 메시지를 나타냄.
<!-- 출력 시점 -->
<level value="DEBUG" />
<!-- 출력 방법 -->
<appender-ref ref="console" />
environment는 여러개가 있을 수 있고, id 값이 default로 들어간다.
sqlSessionFactory
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 프로젝트의 이름 / 데이터베이스와 접속되는 정보 resource 변수에 저장
String resource = "myBatisConfig.xml";
// 설정파일 읽어와서 연결
InputStream is = null;
// 읽어와서 접속준비
try {
// sqlsessionfactory 얻기 / config.xml 파일의 위치인 resource를 통하여 생성
is = Resources.getResourceAsStream(resource);
// SqlSessionFactory는 데이터베이스와의 연결과 SQL의 실행에 대한 모든 것을 가진 가장 중요한 객체
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println("설정 호출");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] : " + e.getMessage());
} finally {
if(is != null) try {is.close();} catch(IOException e) {}
}
}
}
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 프로젝트의 이름
String resource = "myBatisConfig.xml";
// 설정파일 읽어와서 연결
InputStream is = null;
// 핵심적인 역할을 하는 클래스로서 SQL 실행이다 트랙잭션 관리를 실행한다
SqlSession sqlSession = null;
// 읽어와서 접속준비
try {
// sqlsessionfactory 얻기
is = Resources.getResourceAsStream(resource);
// SqlSession을 생성하려면 Mybatis에서는 팩토리 패턴이라는 것을 사용해서 객체를 만듭니다.
// 팩토리 패턴이라는 것은 바로 생성하는게 아니라 특정 객체를 셍성하기 위한 팩토리를 먼저 만들고,
// 그 뒤에 해당 특정 객체를 생성하는 방법
// InputStream을 통해 설정정보를 읽어서 SqlSessionFactory를 빌드한다.
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println("설정 호출");
// openSession 이라는메소드는 세션을 가져오는 메소드
// openSession() 안에 true나 빈 인자값이면 Autocommit / false: AutoCommit을 비활성화된 상태
// SqlSession 은 데이터베이스에 대해 SQL명령어를 실행하기 위해 필요한 모든 메소드를 가지고 있다.
sqlSession = sqlSessionFactory.openSession();
System.out.println("연결 성공");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try {is.close();} catch(IOException e) {}
}
}
}
resultType : select 된 값을 지정해준 곳에 넣겠다는 것(반환유형 정해주는 것)
mapper 태그
SQL mapper 파일들의 정보를 설정한다.
각 mapper 파일을 mapper 태그로 정의한다.
package model1;
public class DeptTO {
private String deptno;
private String dname;
private String loc;
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
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;
}
}
import java.io.IOException;
import java.io.InputStream;
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 model1.DeptTO;
public class MyBatisEx02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 프로젝트의 이름
String resource = "myBatisConfig.xml";
// 설정파일 읽어와서 연결
InputStream is = null;
SqlSession sqlSession = null;
// 읽어와서 접속준비
try {
// sqlsessionfactory 얻기
is = Resources.getResourceAsStream(resource);
// is(InputStream)을 통해 설정정보를 읽어서 SqlSessionFactory를 빌드한다.
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println("설정 호출");
// session
sqlSession = sqlSessionFactory.openSession();
System.out.println("연결 성공");
// 한 줄의 데이터를 가져올 것 인지, 여러 줄의 데이터를 가져올 것 인지에 따라 메서드가 다르다
// 한줄의 데이터 : selectOne / 여러줄의 데이터 : selectList
DeptTO to = (DeptTO)sqlSession.selectOne("selectone"); // mapper의 id값 넣어줌
System.out.println(to.getDeptno());
System.out.println(to.getDname());
System.out.println(to.getLoc());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try {is.close();} catch(IOException e) {}
}
}
}
import java.io.IOException;
import java.io.InputStream;
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 model1.DeptTO;
public class MyBatisEx03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 프로젝트의 이름
String resource = "myBatisConfig.xml";
// 설정파일 읽어와서 연결
InputStream is = null;
SqlSession sqlSession = null;
// 읽어와서 접속준비
try {
// sqlsessionfactory 얻기
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println("설정 호출");
// session
sqlSession = sqlSessionFactory.openSession();
System.out.println("연결 성공");
// 한 줄의 데이터를 가져올 것 인지, 여러 줄의 데이터를 가져올 것 인지에 따라 메서드가 다르다
// 한줄의 데이터 : selectOne / 여러줄의 데이터 : selectList
// 여러줄을 받을때는 List 사용 해줬음
List<DeptTO> lists = sqlSession.selectList("selectall"); // mapper의 id값 넣어줌
for(DeptTO to : lists) {
System.out.println(to.getDeptno());
System.out.println(to.getDname());
System.out.println(to.getLoc());
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try {is.close();} catch(IOException e) {}
}
}
}
// ArrayList로 가져오기
ArrayList<DeptTO> lists = (ArrayList)sqlSession.selectList("selectall");
for(DeptTO to : lists) {
System.out.println(to.getDeptno());
System.out.println(to.getDname());
System.out.println(to.getLoc());
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-35c{1}:%-3L) %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="console" />
</root>
</log4j:configuration>
<?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">
<configuration>
<environments default="mariadb1">
<environment id="mariadb1">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver"/>
<property name="url" value="jdbc:mariadb://localhost:3306/sample"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments >
<mappers>
<mapper resource="model1/mapper.xml" />
</mappers>
</configuration>
<?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="mybatis1">
<select id="selectone" resultType="model1.DeptTO">
select deptno, dname, loc
from dept where deptno=10
</select>
</mapper>
package model1;
public class DeptTO {
private String deptno;
private String dname;
private String loc;
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
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;
}
}
<select id="selectone" resultType="model1.DeptTO">
select deptno, dname, loc
from dept where deptno=10
</select>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%@ page import="model1.DeptTO" %>
<%
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
StringBuilder sbHtml = new StringBuilder();
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
DeptTO to = (DeptTO)sqlSession.selectOne("selectone");
sbHtml.append("<table>");
sbHtml.append("<tr>");
sbHtml.append("<td>" + to.getDeptno() + "</td>");
sbHtml.append("<td>" + to.getDname() + "</td>");
sbHtml.append("<td>" + to.getLoc() + "</td>");
sbHtml.append("</tr>");
sbHtml.append("</table>");
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=sbHtml %>
</body>
</html>
parameterType : 자바에서 String 값이 들어온다는 것
parameterType 정해줌
<select id="selectparamone1" parameterType="String" resultType="model1.DeptTO">
select deptno, dname, loc
from dept where deptno=#{deptno}
</select>
DeptTO to = (DeptTO)sqlSession.selectOne("selectparamone2", "20");
<select id="selectparamone2" resultType="model1.DeptTO">
select deptno, dname, loc
from dept where deptno=#{deptno}
</select>
DeptTO to = (DeptTO)sqlSession.selectOne("selectparamone2", "20");
<select id="selectparamone3" parameterType="model1.DeptTO" resultType="model1.DeptTO">
select deptno, dname, loc
<!-- 두 가지 동시에 / String이 아닌 parameterType이 model1.DeptTO형태 -->
from dept where deptno=#{deptno} and dname=#{dname}
</select>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%@ page import="model1.DeptTO" %>
<%
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
StringBuilder sbHtml = new StringBuilder();
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
DeptTO paramTO = new DeptTO();
paramTO.setDeptno("30");
paramTO.setDname("SALES");
// 3번 실행시키면서 paramTO
DeptTO to = (DeptTO)sqlSession.selectOne("selectparamone3", paramTO);
sbHtml.append("<table>");
sbHtml.append("<tr>");
sbHtml.append("<td>" + to.getDeptno() + "</td>");
sbHtml.append("<td>" + to.getDname() + "</td>");
sbHtml.append("<td>" + to.getLoc() + "</td>");
sbHtml.append("</tr>");
sbHtml.append("</table>");
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=sbHtml %>
</body>
</html>
ename을 통해서 사원정보를 검색하는 .. Mybatis Project 생성
MyBatisEx02 프로젝트 생성하여 새로 만들기
log4j.xml과 myBatisConfig.xml의 설정은 같다.
package model1;
public class EmpTO {
private String empno;
private String ename;
private String job;
private String mgr;
private String hiredate;
private String sal;
private String comm;
private String deptno;
public String getEmpno() {
return empno;
}
public void setEmpno(String empno) {
this.empno = empno;
}
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 getMgr() {
return mgr;
}
public void setMgr(String mgr) {
this.mgr = mgr;
}
public String getHiredate() {
return hiredate;
}
public void setHiredate(String hiredate) {
this.hiredate = hiredate;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getComm() {
return comm;
}
public void setComm(String comm) {
this.comm = comm;
}
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
}
<?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="mybatis1">
<select id="selectparamone1" parameterType="String" resultType="model1.EmpTO">
select empno, ename, job, mgr, hiredate, sal, comm, deptno
from emp
where ename=#{ename}
</select>
<!-- like 구문 사용하기 -->
<select id="selectparamone2" parameterType="String" resultType="model1.EmpTO">
select empno, ename, job, mgr, hiredate, sal, comm, deptno
from emp
where ename like#{ename}
</select>
<select id="selectparamone3" parameterType="String" resultType="model1.EmpTO">
select empno, ename, job, mgr, hiredate, sal, comm, deptno
from emp
where ename like concat(#{ename}, '%')
</select>
</mapper>
<%@page import="model1.EmpTO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%@ page import="model1.EmpTO" %>
<%
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
StringBuilder sbHtml = new StringBuilder();
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
EmpTO to = (EmpTO)sqlSession.selectOne("selectparamone1", "scott");
sbHtml.append("<table>");
sbHtml.append("<tr>");
sbHtml.append("<td>" + to.getEmpno() + "</td>");
sbHtml.append("<td>" + to.getEname() + "</td>");
sbHtml.append("<td>" + to.getJob() + "</td>");
sbHtml.append("<td>" + to.getMgr() + "</td>");
sbHtml.append("<td>" + to.getHiredate() + "</td>");
sbHtml.append("<td>" + to.getSal() + "</td>");
sbHtml.append("<td>" + to.getComm() + "</td>");
sbHtml.append("<td>" + to.getDeptno() + "</td>");
sbHtml.append("</tr>");
sbHtml.append("</table>");
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=sbHtml %>
</body>
</html>
<!-- like 구문 사용하기 -->
<select id="selectparamone2" parameterType="String" resultType="model1.EmpTO">
select empno, ename, job, mgr, hiredate, sal, comm, deptno
from emp
where ename like#{ename}
</select>
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
List<EmpTO> lists = sqlSession.selectList("selectparamone2","s%");
// List<EmpTO> lists = sqlSession.selectList("selectparamone3","s");
sbHtml.append("<table>");
for(EmpTO to : lists) {
sbHtml.append("<tr>");
sbHtml.append("<td>" + to.getEmpno() + "</td>");
sbHtml.append("<td>" + to.getEname() + "</td>");
sbHtml.append("<td>" + to.getJob() + "</td>");
sbHtml.append("<td>" + to.getMgr() + "</td>");
sbHtml.append("<td>" + to.getHiredate() + "</td>");
sbHtml.append("<td>" + to.getSal() + "</td>");
sbHtml.append("<td>" + to.getComm() + "</td>");
sbHtml.append("<td>" + to.getDeptno() + "</td>");
sbHtml.append("</tr>");
}
sbHtml.append("</table>");
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
<select id="selectparamone3" parameterType="String" resultType="model1.EmpTO">
select empno, ename, job, mgr, hiredate, sal, comm, deptno
from emp
where ename like concat(#{ename}, '%')
</select>
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
// List<EmpTO> lists = sqlSession.selectList("selectparamone2","s%");
List<EmpTO> lists = sqlSession.selectList("selectparamone3","s");
sbHtml.append("<table>");
for(EmpTO to : lists) {
sbHtml.append("<tr>");
sbHtml.append("<td>" + to.getEmpno() + "</td>");
sbHtml.append("<td>" + to.getEname() + "</td>");
sbHtml.append("<td>" + to.getJob() + "</td>");
sbHtml.append("<td>" + to.getMgr() + "</td>");
sbHtml.append("<td>" + to.getHiredate() + "</td>");
sbHtml.append("<td>" + to.getSal() + "</td>");
sbHtml.append("<td>" + to.getComm() + "</td>");
sbHtml.append("<td>" + to.getDeptno() + "</td>");
sbHtml.append("</tr>");
}
sbHtml.append("</table>");
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
결과는 동일
transaction
commit - 인정
rollback - 되돌림
<insert id="insert1" parameterType="model1.DeptTO">
insert into dept2(deptno,dname,loc)
values(#{deptno}, #{dname}, #{loc})
</insert>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%@ page import="model1.DeptTO" %>
<%
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
StringBuilder sbHtml = new StringBuilder();
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
DeptTO to = new DeptTO();
to.setDeptno("80");
to.setDname("종무부");
to.setLoc("서울");
int result = sqlSession.insert("insert1", to);
if(result == 1) {
// commit() : 실질적으로 적용을 시킨다는 것.
sqlSession.commit();
sbHtml.append("입력 성공 : " + result);
}
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=sbHtml %>
</body>
</html>
db에 들어간 것을 볼 수 있음. / insert, update, delete를 하면 검사가 되기 전까지는 db에 입력이 안되고 메모리에서 보관해놓는다. / 입력 시키려면 sqlSession.commit()넣기
commit을 계속 해주기 번거로워서 true로 바꿔주면 자동 commit 해준다.
// true : auto commit
sqlSession = sqlSessionFactory.openSession(true);
<update id="update1" parameterType="model1.DeptTO">
update dept2
set dname=#{dname}
where deptno=#{deptno}
</update>
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// true : auto commit
sqlSession = sqlSessionFactory.openSession(true);
DeptTO to = new DeptTO();
to.setDeptno("80");
to.setDname("건두부");
int result = sqlSession.update("update1", to);
if(result == 1) {
sbHtml.append("수정 성공");
}
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
<delete id="delete1" parameterType="model1.DeptTO">
delete from dept2
where deptno=#{deptno}
</delete>
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// true : auto commit
sqlSession = sqlSessionFactory.openSession(true);
DeptTO to = new DeptTO();
to.setDeptno("80");
to.setDname("건두부");
int result = sqlSession.delete("delete1", to);
if(result == 1) {
sbHtml.append("삭제 성공");
}
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) is.close();
}
삭제된 것을 볼 수 있다.
자바 클래스와 자바에 필요한 sql을 별도로 처리
<select id="selectlist" resultType="model1.DeptTO">
select deptno, dname, loc
from dept
</select>
package model1;
import java.io.IOException;
import java.io.InputStream;
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;
public class DeptDAO {
private SqlSession sqlSession;
// sql 세션을 구해서 처리하기
public DeptDAO() {
// TODO Auto-generated constructor stub
String resource = "myBatisConfig.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
this.sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] : " + e.getMessage());
} finally {
if(is != null) try {is.close();} catch(IOException e) {}
}
}
public List<DeptTO> selectList() {
List<DeptTO> lists = sqlSession.selectList("selectlist");
if(sqlSession != null) sqlSession.close();
return lists;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.DeptTO" %>
<%@ page import="model1.DeptDAO" %>
<%@ page import="java.util.List" %>
<%
DeptDAO dao = new DeptDAO();
List<DeptTO> lists = dao.selectList();
StringBuilder sbHtml = new StringBuilder();
sbHtml.append("<table>");
for(DeptTO to : lists) {
sbHtml.append("<tr>");
sbHtml.append("<td>" + to.getDeptno() + "</td>");
sbHtml.append("<td>" + to.getDname() + "</td>");
sbHtml.append("<td>" + to.getLoc() + "</td>");
sbHtml.append("</tr>");
}
sbHtml.append("</table>");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=sbHtml %>
</body>
</html>
MyBatisEx03 다이나믹 프로젝스 생성
model1
ZipcodeTO
ZipcodeDAO
이용하여 만들어보기
<?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="mybatis1">
<select id="selectzipcode1" parameterType="String" resultType="model1.ZipcodeTO">
select zipcode, sido, gugun, dong, ri, bunji, seq from zipcode where dong like #{dong}
</select>
</mapper>
package model1;
public class ZipcodeTO {
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String ri;
private String bunji;
private String seq;
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 getRi() {
return ri;
}
public void setRi(String ri) {
this.ri = ri;
}
public String getBunji() {
return bunji;
}
public void setBunji(String bunji) {
this.bunji = bunji;
}
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
}
package model1;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
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;
public class ZipcodeDAO {
private SqlSession sqlSession;
public ZipcodeDAO() {
// TODO Auto-generated constructor stub
String resource = "myBatisConfig.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
this.sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] : " + e.getMessage());
} finally {
if (is != null) try {is.close();} catch (IOException e) {}
}
}
public ArrayList<ZipcodeTO> selectList(String strDong) {
ArrayList<ZipcodeTO> lists = (ArrayList)sqlSession.selectList("selectzipcode1", strDong + "%");
if(sqlSession != null) sqlSession.close();
return lists;
}
}
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="model1.ZipcodeTO"%>
<%@page import="model1.ZipcodeDAO"%>
<%@ page import="java.util.List" %>
<%
request.setCharacterEncoding("utf-8");
String strDong = null;
if(request.getParameter("dong") != null) {
strDong = request.getParameter("dong");
}
ZipcodeDAO dao = new ZipcodeDAO();
ArrayList<ZipcodeTO> lists = dao.selectList(strDong);
StringBuilder sbHtml = new StringBuilder();
sbHtml.append("<table>");
for(ZipcodeTO to : lists) {
sbHtml.append("<tr>");
sbHtml.append("<td>" + to.getZipcode() + "</td>");
sbHtml.append("<td>" + to.getSido() + "</td>");
sbHtml.append("<td>" + to.getGugun() + "</td>");
sbHtml.append("<td>" + to.getDong() + "</td>");
sbHtml.append("<td>" + to.getRi() + "</td>");
sbHtml.append("<td>" + to.getBunji() + "</td>");
sbHtml.append("<td>" + to.getSeq() + "</td>");
sbHtml.append("</tr>");
}
sbHtml.append("</table>");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="zipcode.jsp" method="post" >
동이름 입력 : <input type="text" name="dong" />
<input type="submit" value="전송" />
</form>
<%=sbHtml %>
</body>
</html>
실행
실행 후 검색
Model1Ex1 프로젝트를 복사하여 MyBatisModel1Ex1 로 만들고 세팅
<?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="mybatis1">
<select id="list" resultType="model1.BoardTO">
select seq, subject, writer, wdate, hit
from board1 order by seq desc
</select>
<select id="view" parameterType="model1.BoardTO" resultType="model1.BoardTO">
select seq, subject, writer, mail, wip, wdate, hit, content
from board1
where seq=#{seq}
</select>
<update id="view_hit" parameterType="model1.BoardTO">
update board1
set hit=hit+1
where seq=#{seq}
</update>
<insert id="write_ok" parameterType="model1.BoardTO">
insert into board1
values(0,#{subject},#{writer},#{mail},#{password},#{content},0,#{wip},now())
</insert>
<select id="modify" parameterType="model1.BoardTO" resultType="model1.BoardTO">
select seq, subject, writer, mail, content
from board1
where seq=#{seq}
</select>
<update id="modify_ok" parameterType="model1.BoardTO" >
update board1 set subject=#{subject}, mail=#{mail}, content=#{content}
where seq=#{seq} and password=#{password}
</update>
<select id="delete" parameterType="model1.BoardTO" resultType="model1.BoardTO">
select seq, subject, writer
from board1
where seq=#{seq}
</select>
<delete id="delete_ok" parameterType="model1.BoardTO">
delete from board1
where seq=#{seq} and password=#{password}
</delete>
</mapper>
package model1;
public class BoardTO {
// 게시판의 데이터를 처리하기 위해 선언
private String seq;
private String subject;
private String writer;
private String mail;
private String password;
private String content;
private String hit;
private String wip;
private String wdate;
private int wgap;
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
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 getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getHit() {
return hit;
}
public void setHit(String hit) {
this.hit = hit;
}
public String getWip() {
return wip;
}
public void setWip(String wip) {
this.wip = wip;
}
public String getWdate() {
return wdate;
}
public void setWdate(String wdate) {
this.wdate = wdate;
}
public int getWgap() {
return wgap;
}
public void setWgap(int wgap) {
this.wgap = wgap;
}
}
package model1;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class BoardDAO {
private SqlSession sqlSession;
// 생성자가 필요
public BoardDAO() {
String resource = "myBatisConfig.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession(true);
} catch(IOException e) {
System.out.println("[에러] : " + e.getMessage());
}
}
/*
이것들에 해당하는 메서드 선언
write / write_ok / list/ view / modify / modify_ok / delete / delete_ok
*/
public void boardWrite() {
}
// BoardTO to는 write에서 받은 데이터를 집어넣는다
public int boardWriteOk(BoardTO to) {
int flag = 1;
int result = sqlSession.insert("write_ok", to);
if(result == 1) {
flag = 0;
}
if(sqlSession != null) sqlSession.close();
return flag;
}
// list는 ArrayList로 받아온다
public ArrayList<BoardTO> boardList() {
ArrayList<BoardTO> datas = (ArrayList)sqlSession.selectList("list");
if(sqlSession != null) sqlSession.close();
return datas;
}
// to에 seq가 들어가서 update하고 select 함
public BoardTO boardView(BoardTO to) {
sqlSession.update("view_hit", to);
to = sqlSession.selectOne("view", to);
return to;
}
public BoardTO boardModify(BoardTO to) {
to = sqlSession.selectOne("modify", to);
if(sqlSession != null) sqlSession.close();
return to;
}
public int boardModifyOk(BoardTO to) {
int flag = 2;
int result = sqlSession.update("modify_ok", to);
if(result == 1) {
flag = 0;
} else if(result == 0) {
flag = 1;
}
if(sqlSession != null) sqlSession.close();
return flag;
}
public BoardTO boardDelete(BoardTO to) {
to = sqlSession.selectOne("delete", to);
if(sqlSession != null) sqlSession.close();
return to;
}
public int boardDeleteOk(BoardTO to) {
int flag = 2;
int result = sqlSession.delete("delete_ok", to);
if(result == 1) {
flag = 0;
} else if(result == 0) {
flag = 1;
}
return flag;
}
}