class 30 - jsp에서 myBatis

yoneeki·2023년 3월 16일
0

training-jp

목록 보기
20/31

JSP에서 MyBatis

myBatis 라이브러리

  • maven repository에서 myBatis.jar 파일을 다운받아 프로젝트에 설정시킴

MyBatis란

  • 자바에서 SQL Mapper를 지원하는 프레임워크

폴더 구조

  • 기존에는 DAO에 SQL문을 다 넣고 처리했는데 이제는 관련 로직을 myBatis로 처리

DAO

package com.jjang051.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

public class BoardDao {
	public int insertBoard(BoardDto boardDto) {
		int result = 0;
		SqlSession sqlSession = MybatisConnectionFactory.getSqlSession();
		result = sqlSession.insert
				("insertBoard",boardDto);
		if(result>0) {
			sqlSession.commit();
		} else {
			sqlSession.rollback();
		}
		sqlSession.close();
		return result;
	}
	public List<BoardDto> getAllBoard() {
		List<BoardDto> boardList = null;
		SqlSession sqlSession = MybatisConnectionFactory.getSqlSession();
		boardList = sqlSession.selectList("getAllBoard");
		sqlSession.close();
		return boardList;
	}
	public BoardDto getSelectOne(int no) {
		BoardDto boardDto = null;
		SqlSession sqlSession = MybatisConnectionFactory.getSqlSession();
		boardDto = sqlSession.selectOne("getSelectOne",no);
		sqlSession.close();
		return boardDto;
	}
	public int updateHit(int no) {
		int result = 0;
		SqlSession sqlSession = MybatisConnectionFactory.getSqlSession();
		result = sqlSession.update("updateHit",no);
		sqlSession.commit();
		sqlSession.close();
		return result;
		
	}
	
	
}

MybatisConnectionFactory

package com.jjang051.model;

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 MybatisConnectionFactory {
	private static SqlSessionFactory sqlSessionFactory;
	static {
		try {
			String resource = "com/jjang051/mybatis/config.xml";
			InputStream inputStream;
			inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	// 싱글턴 패턴
	public static SqlSession getSqlSession() {
		return sqlSessionFactory.openSession();
	}
}

myBatis 관련 폴더 내부

BoardMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jjang051.mybatis.board">
	<!-- select는 resultType과 parameterType을 가질 수 있다.  id는 dao의 메서드 명이랑 일치 시켜주면 된다.-->
	<select id="getAllBoard" resultType="BoardDto">
		SELECT * FROM BOARD03 ORDER BY NO
	</select>
	<select id="getSelectOne" parameterType="Integer" resultType="BoardDto">
		SELECT * FROM BOARD03 WHERE NO = #{no}
	</select>
	<!-- insert, delete, update는 resultType이 없다 -->
	<insert id="insertBoard" parameterType="BoardDto">
		INSERT INTO BOARD03 VALUES (BOARD03_SEQ.NEXTVAL,
									#{userName},
									#{subject},
									#{contents},
									SYSDATE,
									0
									
		)
	</insert>
	<update id="updateHit" parameterType="Integer">
		UPDATE BOARD03 SET HIT = HIT + 1 WHERE NO = #{no}
	</update>
</mapper>

config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="com/jjang051/mybatis/db.properties"></properties>
	<typeAliases>
		<typeAlias type="com.jjang051.model.BoardDto" alias="BoardDto" />
	</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="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/jjang051/mybatis/BoardMapper.xml" />
	</mappers>
</configuration>

db.properties

driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username= // db명 (따옴표없이)
password= // db pwd (따옴표없이)

myBatis가 제공하는 crud 메서드

  • chat gpt 한테 물어서 얻어낸 답변

MyBatis is a popular Java persistence framework that provides a simple and intuitive way to interact with a database using SQL queries. It provides support for CRUD operations (Create, Read, Update, and Delete) through the following methods:

Create (INSERT): To insert new data into a database, MyBatis provides the insert method. The insert method takes an object that represents the data to be inserted and maps it to the appropriate SQL statement.

Read (SELECT): To retrieve data from a database, MyBatis provides the selectOne and selectList methods. The selectOne method returns a single object that matches the query, while the selectList method returns a list of objects that match the query.

Update (UPDATE): To update data in a database, MyBatis provides the update method. The update method takes an object that represents the updated data and maps it to the appropriate SQL statement.

Delete (DELETE): To delete data from a database, MyBatis provides the delete method. The delete method takes an object that represents the data to be deleted and maps it to the appropriate SQL statement.

In addition to these methods, MyBatis also provides support for parameter mapping, result mapping, dynamic SQL generation, and many other features that make working with databases easier and more efficient. Overall, MyBatis provides a flexible and powerful way to interact with databases in Java, and is widely used in many enterprise applications.

update로 더 자세히 살펴보기

데이터가 넘어가는 로직

  • list 화면에서 한 글에 대한 view를 클릭하면 쿼리스트링으로 pk인 no가 넘어감
  • view 화면에서 수정하기 버튼을 누르면 역시나 쿼리스트링으로 pk인 no를 넘김
  • 이 과정에서 데이터는 jsp로 바로 넘어가는 게 아니라 뷰를 반환하는 서블릿으로 넘어가기 때문에, 서블릿에서 request.getParameter("no")를 받고 request.setAttribute("no", no) 혹은 request.setAttribute("dto", dto)를 설정한 후 dispatcher.forward(request, response) 를 실행
  • modify는 보이지 않는 곳에 (ex. input hidden) no를 실어서 modifyProcessController 서블릿으로 no를 넘김

BoardMapper.xml

<update id="updateBoard" parameterType="BoardDto">
		UPDATE BOARD03 SET userName=#{userName}, subject=#{subject}, contents=#{contents} WHERE NO = #{no}
	</update>

BoardDao.java

public int updateBoard(BoardDto boardDto) {
		int result = 0;
		SqlSession sqlSession = MybatisConnectionFactory.getSqlSession();
		result = sqlSession.insert
				("updateBoard",boardDto);
		if(result>0) {
			sqlSession.commit();
		} else {
			sqlSession.rollback();
		}
		sqlSession.close();
		return result;
	}

BoardModifyProcessController.java

package com.jjang051.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jjang051.model.BoardDao;
import com.jjang051.model.BoardDto;
import com.jjang051.util.ScriptWriter;

@WebServlet("/board/modifyProcess")
public class BoardModifyProcessController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		BoardDto boardDto = new BoardDto();
		boardDto.setNo(Integer.parseInt(request.getParameter("no")));
		boardDto.setUserName(request.getParameter("userName"));
		boardDto.setSubject(request.getParameter("subject"));
		boardDto.setContents(request.getParameter("contents"));
		BoardDao boardDao = new BoardDao();
		int result = boardDao.updateBoard(boardDto);
		if (result > 0) {
			ScriptWriter.alertAndNext(response, "글이 입력되었습니다.", "../board/list");
		} else {
			ScriptWriter.alertAndBack(response, "수정 시 문제 발생, 다시 시도.");
			System.out.println(boardDto.toString());
		}
	}

}
profile
Working Abroad ...

0개의 댓글