SqlSession
MyBatis는 데이터베이스와의 상호작용을 위해 SqlSession 객체를 사용
데이터베이스 트랜잭션을 시작하고, SQL 매퍼 구문을 실행하며, 결과를 가져오는 등
데이터베이스와의 모든 상호작용을 처리하는 주요 객체
SqlSessionFactory
MyBatis의 핵심 인터페이스로, 데이터베이스 연결을 설정하고 SqlSession을 생성하는 역할을 합니다.
openSession() 메서드를 호출하면 SqlSession 객체가 반환
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSessionFactory를 사용하여 데이터베이스와의 세션을 열고 SqlSession 객체를 생성하는 부분입니다.
이후에는 sqlSession 객체를 사용하여 데이터베이스와의 상호작용을 수행할 수 있습니다.
서블릿 마이바티스 사용할 때 밑에 코드 맨 윗 줄에 위치
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 마이바티스 환경 설정 XML 파일 경로
String resource = "resources/mybatis/config-mybatis.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
마이바티스 EmpMapper.xml에서 데이터 내역 가져오기 ( Select )
Mapper.xml
<select id="selectGoods" resultType="com.db.Goods">
select num, thing, recdate
from goods
</select>
resultType = "DTO 경로"
Servlet.java
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 조회 매핑 구문 실행
List<Object> list = sqlSession.selectList("org.mybatis.persistence.EmpMapper.selectGoods");
request.setAttribute("list", list);
request.getRequestDispatcher("index-result.jsp")
.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 세션 및 트랜잭션 종료
sqlSession.close();
}
request.setAttribute("list", list);는 JSP와 Servlet 간에 데이터를 전달하는 방법 중 하나인 "request 스코프"를 이용하는 코드
JSP 페이지에서 ${키}를 사용하여 해당 데이터에 접근할 수 있다
list라는 데이터를 "list"라는 이름으로 JSP 페이지에 전달할 수 있게 된다.
jsp에서 itemList = ${list}; 이렇게 하고 html 부분에 <div id="itemList">하게 되면 해당 부분 출력 가능
request.getRequestDispatcher("index-result.jsp").forward(request, response);
index-result.jsp라는 JSP 파일로 서블릿의 처리 결과를 넘겨주고,
해당 JSP 페이지에서 클라이언트에게 결과를 표시하도록 하는 역할
마이바티스 EmpMapper.xml에서 데이터 추가 ( Insert )
서블릿 마이바티스 세션 연결 코드는 동일
Mapper.xml
<insert id="insertGoods" parameterType="com.db.Goods">
<selectKey keyProperty="num" resultType="java.lang.Integer"
order="BEFORE">
select SEQ_GOODS.NEXTVAL from dual
</selectKey>
insert into goods(num, thing, recdate)
values(#{num}, #{thing}, sysdate)
</insert>
selectKey로 시퀀스 num값 자동으로 받아오기 가능
Servlet.java
String thing = request.getParameter("thing");
// 세션 및 트랜잭션 시작
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 새로 고침 안해도 번호 받아오기
Goods goods = new Goods(0, thing, null);
// 조회 매핑 구문 실행
int res = sqlSession.insert("org.mybatis.persistence.EmpMapper.insertGoods"
, goods);
response.getWriter().print(goods.getNum());
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 세션 및 트랜잭션 종료
sqlSession.close();
}
"thing" 파라미터의 값을 가져오는 역할
"thing" 파라미터를 전달하지 않았을 경우, null이 반환
서버에서 "thing" 값을 보내주면 서블릿에서 받아서 Mapper.insertGoods로 전달해서 마이바티스가 DB에 저장
Goods goods = new Goods(0, thing, null);
int res = sqlSession.insert("org.mybatis.persistence.EmpMapper.insertGoods"
, goods);
이렇게 작성 안하고
int res = sqlSession.insert("org.mybatis.persistence.EmpMapper.insertGoods"
, new Goods(0, thing, null));
이렇게 작성시 insert는 되나 동적으로 num값을 가져올 수 없고 새로고침 해야됨
마이바티스 EmpMapper.xml에서 데이터 제거 ( Delete )
Mapper.xml
<delete id="deleteGoods" parameterType="int">
delete from goods where num = #{num}
</delete>
Servlet.java
int num = Integer.parseInt(request.getParameter("num"));
// 세션 및 트랜잭션 시작
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 조회 매핑 구문 실행
int res = sqlSession.delete("org.mybatis.persistence.EmpMapper.deleteGoods",
num);
response.getWriter().print(res);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 세션 및 트랜잭션 종료
sqlSession.close();
}
int num = Integer.parseInt(request.getParameter("num"));
클라이언트에서 서버로 전달된 "num" 파라미터 값을 가져와서 String 타입에서 int 타입으로 변환
전달된 값은 String 타입이기때문에 int타입으로 변환 필요
나머지는 insert와 동일
// 클라이언트 측에서 관리되는 배열로, 데이터 베이스 내용을 담음
let itemList = [];
const addBtn = document.querySelector("#add"); // 버튼의 id
//클릭 이벤트가 발생하면 addList() 함수가 실행되도록 함
addBtn.addEventListener("click", addList);
// insert 함수
function addList() {
// 사용자가 입력한 값(HTML)을 나타내는 input 요소
let str = document.querySelector("#item");
// 비동기적인 서버와의 통신을 수행할 준비를 함
const xhr = new XMLHttpRequest();
if (str.value != null && str.value != '') {
let num;
console.log(str.value);
// 서버로 보낼 요청을 설정
// GET 방식으로 'ExecAjax' 서블릿에 'thing'이라는 파라미터와 함께 사용자가 입력한 값을 전달
xhr.open('GET', 'ExecAjax?thing=' + str.value, true);
xhr.send();// 서버로 요청을 전송
// 서버에서 응답이 도착했을 때 실행될 함수를 지정
xhr.onload= ()=>{
if(xhr.status == 200){
console.log("성공")
num = xhr.responseText;// 서버에서 반환된 응답 데이터를 num 변수에 저장
//서버 응답으로 받은 num 값과 사용자가 입력한 str.value 값을 객체 형태로 itemList 배열에 추가
itemList.push({idx:num, thing:str.value});
str.value = '';
str.focus();// 입력한 아이템 값을 비워주고, 다시 입력할 수 있도록 입력 필드에 포커스
showList();// 리스트를 갱신
}else{
console.log("실패");
}
}
}
}
// itemList 배열에 있는 데이터를 가지고 HTML에 리스트 형태로 표시하는 역할
function showList() {
let list = "<ul>";
for(let i=0; i < itemList.length; i++) {
list += `<li>${itemList[i].thing}<span class='close' id='${itemList[i].idx}'>X</span></li>`;
}
list += "</ul>";
document.querySelector("#itemList").innerHTML = list; // div의 id
let remove = document.querySelectorAll(".close");
//console.log(remove);
for(let i = 0; i < remove.length; i++) {
remove[i].addEventListener("click", removeList);
}
}
function removeList() {
const xhr = new XMLHttpRequest();
let id = this.getAttribute("id");
xhr.open('GET', 'DelServ?num=' + id, true);
xhr.send();
xhr.onload= ()=>{
if(xhr.status == 200){
console.log("성공")
let num = xhr.responseText;
}else{
console.log("실패");
}
}
//console.log(id);
//itemList.splice(id, 1);
itemList = itemList.filter(t => t.idx != id);
showList();
}
'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정 > 추가 복습' 카테고리의 다른 글
오라클 정리 (0) | 2023.07.24 |
---|---|
스프링 정리 (0) | 2023.07.22 |
이클립스 URL에 프로젝트 이름 안 나오게 하기 (0) | 2023.07.20 |
이클립스 톰캣 버전 안 맞을 때 에러 해결 (0) | 2023.07.18 |
스프링_maven_설정 (0) | 2023.07.18 |