본문 바로가기

Server Programming/Spring Backend Programming

[Spring 입문] 3. 스프링 프레임워크를 이용한 게시판 구축 (2)

반응형

스프링 MVC

인텔리제이에서 스프링MVC를 사용해 프로젝트를 구성한다면, 

이클립스와의 시스템과 충돌이 발생한다.

 

개발 환경 구축

1. servlet-context.xml 설정

2. root-context.xml 설정

3. web.xml 설정

4. pom.xml를 통한 의존성 추가


servlet-context.xml

1. 네임스페이스 추가 -> 주소를 이용해 추가한다. -> 인텔리제이의 경우 자동 추가된다.

2. 어노테이션을 인식해주는 설정, 디스패처서블릿으로 매핑해주는 설정, 리소스 파일 위치 설정

3. 빈 등록을 위한 어노테이션 인식해주는 설정, 빈을 위한 컴포넌트 스캔 설정

4. 뷰의 위치를 미리 알려주는 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- This tag registers the DefaultAnnotationHandlerMapping and
         AnnotationMethodHandlerAdapter beans that are required for Spring MVC  -->
    <mvc:annotation-driven />
    <!-- This tag allows for mapping the DispatcherServlet to "/" -->
    <mvc:default-servlet-handler />

    <!-- Process annotations on registered beans like @Autowired... -->
    <context:annotation-config/>
    <!-- 컴포넌트 스캔 -->
    <context:component-scan base-package="com.springboard.mvc" />

    <!-- resources가 아니라 mvc:resources-->
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

root-context.xml

1. 네임스페이스 추가

2. 오라클 DB 설정

(1) dataSource

(2) sqlSessionFactory

(3) sqlSessionTemplate

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!-- DB정보를 가지는 datasource 빈객체 생성-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="false">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
        <property name="username" value="system" />
        <property name="password" value="pass"/>
    </bean>

    <!-- DB정보를 자기는 datasource와 쿼리문을 작성하는 Mapper.xml이 있는 경로 설정하는 mapperLocations를
    - 포함하는 빈 객체 생성-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="resources/sqlmap/config/mybatis-config.xml"></property>
        <property name="mapperLocations" value ="/resources/sqlmap/sqlmap-board.xml"></property>
    </bean>

    <!-- DB정보를 자기는 datasource와 쿼리문을 작성하는 Mapper.xml이 있는 경로 설정하는 mapperLocations를
    - 포함하는 빈 객체를 가지는 sqlSessionTemplate 생성 <- 실제로 Mapper.java에서 주입을 통해 사용함-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory"></constructor-arg>
    </bean>

</beans>

web.xml

: 톰캣에 존재하는 설정파일인데, 인텔리제이에서 컨텍스트 설정 파일 위치를 명시한다.

1. 루트 컨텍스트 위치 명시

2. 스프링 컨테이너를 공유하도록 리스너를 설정

3. 서블릿 컨텍스트 위치 명시

4. 한글 입력 설정

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/root-context.xml</param-value>
  </context-param>

  <!-- Creates the Spring Container shared by all Servlets and Filters -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- Processes application requests -->
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- Start: POST 입력 한글문제 처리 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- Finish: POST 입력 한글문제 처리 -->

</web-app>

더보기

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.board</groupId>
  <artifactId>mvc</artifactId>
  <name>board</name>
  <packaging>war</packaging>
  <version>1.0.0-BUILD-SNAPSHOT</version>
  <!-- oracle 의존성 추가 1-->

  <!-- properties 보다 위에 넣어주도록 하자 -->
  <repositories>
    <repository>
      <id>oracle</id>
      <url>http://maven.jahia.org/maven2</url>
    </repository>
  </repositories>


  <properties>
    <java-version>1.8</java-version>
    <org.springframework-version>5.3.23</org.springframework-version>
    <org.aspectj-version>1.9.9.1</org.aspectj-version>
    <org.slf4j-version>2.0.1</org.slf4j-version>
  </properties>

  <dependencies>
    <!-- 오라클용 추가 시작-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency> <!-- Oracle -->
    <dependency>
      <groupId>com.oracle.database.jdbc</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.4</version>
    </dependency>
    <!-- 오라클용 추가 끝-->

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
      <groupId>org.bgee.log4jdbc-log4j2</groupId>
      <artifactId>log4jdbc-log4j2-jdbc4</artifactId>
      <version>1.16</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.7</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.11</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework-version}</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.14.Final</version>
    </dependency>


    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework-version}</version>
      <exclusions>
        <!-- Exclude Commons Logging in favor of SLF4j -->
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework-version}</version>
    </dependency>

    <!-- AspectJ -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>${org.aspectj-version}</version>
    </dependency>

    <!-- Logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${org.slf4j-version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${org.slf4j-version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${org.slf4j-version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.15</version>
      <exclusions>
        <exclusion>
          <groupId>javax.mail</groupId>
          <artifactId>mail</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.jms</groupId>
          <artifactId>jms</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jdmk</groupId>
          <artifactId>jmxtools</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jmx</groupId>
          <artifactId>jmxri</artifactId>
        </exclusion>
      </exclusions>
      <scope>runtime</scope>
    </dependency>
    <!--notempty와 length -->
    <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.1.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
      <version>2.5.4</version>
    </dependency>

    <!-- @Inject -->
    <dependency>
      <groupId>javax.inject</groupId>
      <artifactId>javax.inject</artifactId>
      <version>1</version>
    </dependency>

    <!-- Servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- Test -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
<!-- xml 한글 문제 처리-->
    <dependency>
      <groupId>xerces</groupId>
      <artifactId>xercesImpl</artifactId>
      <version>2.9.1</version>
    </dependency>

  </dependencies>
  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
          <compilerArgument>-Xlint:all</compilerArgument>
          <showWarnings>true</showWarnings>
          <showDeprecation>true</showDeprecation>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <configuration>
          <mainClass>org.test.int1.Main</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

패키지 계층구조는 com.springboard.mvc로, 

컨트롤러, dao, service로 구분했다.

 

1. controller

BoardController.java

package com.springboard.mvc.board.controller;

import com.springboard.mvc.board.domain.BoardVO;
import com.springboard.mvc.board.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.validation.Valid;

@Controller
@SessionAttributes("boardVO")
public class BoardController {
	@Autowired
	private BoardService boardService;

	public BoardService getBoardService() {
		return boardService;
	}

	public void setBoardService(BoardService boardService) {
		this.boardService = boardService;
	}

	@RequestMapping(value = "/board/list")
	public String list(Model model) {
		model.addAttribute("boardList", boardService.list());
		return "/board/list";
	}

	@RequestMapping(value = "/board/read/{seq}")
	public String read(Model model, @PathVariable int seq) {
		model.addAttribute("boardVO", boardService.read(seq));
		return "/board/read";
	}

	@RequestMapping(value = "/board/write", method = RequestMethod.GET)
	public String write(Model model) {
		model.addAttribute("boardVO", new BoardVO());
		return "/board/write";
	}

	@RequestMapping(value = "/board/write", method = RequestMethod.POST)
	public String write(@Valid BoardVO boardVO, BindingResult bindingResult, SessionStatus sessionStatus) {
		if (bindingResult.hasErrors()) {
			return "/board/write";
		} else {
			boardService.write(boardVO);
			sessionStatus.setComplete();
			return "redirect:/board/list";
		}
	}

	@RequestMapping(value = "/board/edit", method = RequestMethod.GET)
	public String edit(@ModelAttribute BoardVO boardVO) {
		return "/board/edit";
	}

	@RequestMapping(value = "/board/edit", method = RequestMethod.POST)
	public String edit(@Valid @ModelAttribute BoardVO boardVO,
			BindingResult result, int pwd, SessionStatus sessionStatus,
			Model model) {
		if (result.hasErrors()) {
			return "/board/edit";
		} else {
			if (boardVO.getPassword() == pwd) {
				boardService.edit(boardVO);
				sessionStatus.setComplete();
				return "redirect:/board/list";
			}

			model.addAttribute("msg", "비밀번호가 일치하지 않습니다.");
			return "/board/edit";
		}
	}

	@RequestMapping(value = "/board/delete/{seq}", method = RequestMethod.GET)
	public String delete(@PathVariable int seq, Model model) {
		model.addAttribute("seq", seq);
		return "/board/delete";
	}

	@RequestMapping(value = "/board/delete", method = RequestMethod.POST)
	public String delete(int seq, int pwd, Model model) {
		int rowCount;
		BoardVO boardVO = new BoardVO();
		boardVO.setSeq(seq);
		boardVO.setPassword(pwd);

		rowCount = boardService.delete(boardVO);

		if (rowCount == 0) {
			model.addAttribute("seq", seq);
			model.addAttribute("msg", "비밀번호가 일치하지 않습니다.");
			return "/board/delete";
		} else {
			return "redirect:/board/list";
		}
	}

	@RequestMapping(value = "/test")
	@ResponseBody
	public String test(String name, int age) {
		return "<h1>" + name + age + "</h1>";
	}
}

2. dao

인터페이스 BoardDao와 구현하는 클래스

 

BoardDao.java

package com.springboard.mvc.board.dao;

import com.springboard.mvc.board.domain.BoardVO;

import java.util.List;

public interface BoardDao {
	public abstract List<BoardVO> list();

	public abstract int delete(BoardVO boardVO);
	
	public abstract int deleteAll();

	public abstract int update(BoardVO boardVO);

	public abstract void insert(BoardVO boardVO);

	public abstract BoardVO select(int seq);

	public abstract int updateReadCount(int seq);
}

 

BoardDaoMyBatis.java

package com.springboard.mvc.board.dao;

import com.springboard.mvc.board.domain.BoardVO;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class BoardDaoMyBatis implements BoardDao {
	private SqlSessionTemplate sqlSessionTemplate;

	@Autowired
	public void setSqlMapClient(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	@Override
	public List<BoardVO> list() {
		return sqlSessionTemplate.selectList("list");
	}

	@Override
	public int delete(BoardVO boardVO) {
		return sqlSessionTemplate.delete("delete", boardVO);
	}

	@Override
	public int deleteAll() {
		return sqlSessionTemplate.delete("deleteAll");
	}

	@Override
	public int update(BoardVO boardVO) {
		return sqlSessionTemplate.update("update", boardVO);
	}

	@Override
	public void insert(BoardVO boardVO) {
		sqlSessionTemplate.insert("insert", boardVO);
	}

	@Override
	public BoardVO select(int seq) {
		BoardVO vo = (BoardVO) sqlSessionTemplate.selectOne("select", seq);
		return vo;
	}

	@Override
	public int updateReadCount(int seq) {
		return sqlSessionTemplate.update("updateCount", seq);
	}
}

3. domain

BoardVO.java

package com.springboard.mvc.board.domain;

import org.apache.ibatis.type.Alias;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

import java.sql.Timestamp;

@Alias("boardVO")
public class BoardVO {
	private int seq;
	@Length(min=2, message="제목은 2자 이상 입력하세요.")
	private String title;
	@NotEmpty(message = "내용을 입력하세요.")
	private String content;
	@NotEmpty(message = "작성자를 입력하세요.")
	private String writer;
	private int password;
	private Timestamp regDate;
	private int cnt;
	
	public BoardVO() { }
	
	public BoardVO(String title, String content, String writer, int password) {
		super();
		this.title = title;
		this.content = content;
		this.writer = writer;
		this.password = password;		
		this.cnt = 0;
	}

	public int getSeq() {
		return seq;
	}

	public void setSeq(int seq) {
		this.seq = seq;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getWriter() {
		return writer;
	}

	public void setWriter(String writer) {
		this.writer = writer;
	}

	public int getPassword() {
		return password;
	}

	public void setPassword(int password) {
		this.password = password;
	}

	public Timestamp getRegDate() {
		return regDate;
	}

	public void setRegDate(Timestamp regDate) {
		this.regDate = regDate;
	}

	public int getCnt() {
		return cnt;
	}

	public void setCnt(int cnt) {
		this.cnt = cnt;
	}
}

4. service

인터페이스 BoardService와 구현하는 클래스

 

BoardService.java

package com.springboard.mvc.board.service;

import com.springboard.mvc.board.domain.BoardVO;

import java.util.List;

public interface BoardService {
	public abstract List<BoardVO> list();

	public abstract int delete(BoardVO boardVO);
	
	public abstract int edit(BoardVO boardVO);

	public abstract void write(BoardVO boardVO);

	public abstract BoardVO read(int seq);
}

 

BoardServiceImpl.java

package com.springboard.mvc.board.service;

import com.springboard.mvc.board.dao.BoardDao;
import com.springboard.mvc.board.domain.BoardVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BoardServiceImpl implements BoardService {
	@Resource
	private BoardDao boardDao;

	public BoardDao getBoardDao() {
		return boardDao;
	}

	public void setBoardDao(BoardDao boardDao) {
		this.boardDao = boardDao;
	}

	@Override
	public List<BoardVO> list() {
		return boardDao.list();
	}

	@Override
	public int delete(BoardVO boardVO) {
		return boardDao.delete(boardVO);
	}

	@Override
	public int edit(BoardVO boardVO) {
		return boardDao.update(boardVO);
	}

	@Override
	public void write(BoardVO boardVO) {
		boardDao.insert(boardVO);
	}

	@Override
	public BoardVO read(int seq) {
		boardDao.updateReadCount(seq);
		return boardDao.select(seq);
	}
}

 

사용 스택

1. JSP와 JSTL -> 자바 서버 태그 라이브러리

(1) 의존성 추가

(2) jsp파일에서 taglib 설정

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" 
  content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <table border="1">
    <tr>
      <th>NO</th>
      <th>제목</th>
      <th>작성자</th>
      <th>작성일</th>
      <th>조회수</th>
    </tr>
    <c:forEach var="board" items="${boardList}" 
      varStatus="loop">
      <tr>
        <td>${board.seq}</td>
        <td><a href=
"<c:url value="/board/read/${board.seq}" />">
          ${board.title}</a></td>
        <td>${board.writer}</td>
        <td>${board.regDate}</td>
        <td>${board.cnt}</td>
      </tr>
    </c:forEach>
  </table>
  <a href="<c:url value="/board/write" />">새글</a>
</body>
</html>

 

2. MyBatis

(1) root-context에 빈 객체를 생성한다.

dataSource : DB정보를 가지는 빈 객체 생성

sqlSessionFactory : dataSource 설정, configLocation설정, mapperLocations 설정

sqlSessionTemplate : DB정보와 쿼리문 작성하는 맵퍼를 포함하는 빈 객체 생성

 

(2) 객체-관계 매핑

sqlmap-board.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="boardDAO">
	<select id="list" resultType="boardVO">
		SELECT * FROM BOARD
		ORDER BY seq
	</select>

	<select id="select" parameterType="int" resultType="boardVO">
		SELECT * FROM
		BOARD WHERE seq = #{seq}
	</select>

	<insert id="insert" parameterType="boardVO">
		INSERT INTO BOARD
		(title, content, writer, password, regDate, cnt)
		VALUES
		(#{title}, #{content}, #{writer}, #{password}, SYSDATE, 0);
		<selectKey keyProperty="seq" resultType="Integer">
			SELECT NVL(MAX(seq),
			0) FROM BOARD
		</selectKey>
	</insert>

	<update id="update" parameterType="boardVO">
		UPDATE BOARD SET
		title = #{title}
		, content = #{content}
		, writer = #{writer}
		WHERE seq = #{seq}
		AND password = #{password}
	</update>

	<update id="updateCount" parameterType="int">
		UPDATE BOARD SET
		cnt = cnt + 1
		WHERE seq = #{seq}
	</update>

	<delete id="delete" parameterType="boardVO">
		DELETE FROM BOARD
		WHERE seq = #{seq}
		AND password = #{password}
	</delete>

	<delete id="deleteAll">
		DELETE FROM BOARD
	</delete>
</mapper>

(3) 마이바티스 환경 설정

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">
<configuration>
	<!-- 마이바티스의 작동 규칙정의 -->
	<settings>
	  <setting name="cacheEnabled" value="false"/>
	  <setting name="useGeneratedKeys" value="false"/>
	  <setting name="mapUnderscoreToCamelCase" value="true"/>
	</settings>

	<typeAliases>
		<typeAlias alias="boardVO" type="com.springboard.mvc.board.domain.BoardVO" />
	</typeAliases>
</configuration>

 

3. 도커와 오라클

[애플 실리콘에서 가상환경 도커에 오라클을 설치해서 사용]

반응형