9_Spring(파일업로드2)

study/Spring · 2020. 3. 11. 08:28

BoardService(interface) ->BoardServiceImpl

게시글 등록용 Service
@Transactional(rollbackFor = Exception.class)
@Override
public int insertBoard(Board board, List<Attachment> files) throws Exception

	int result = 0;
    
    // 1)  다음 SEQ_BNO 얻어오기
    int boardNo = boardDAO.selectNextNo();
    
    // 2) 게시글 (board) DB 삽입
    if(boardNo > 0) {
    	// DB에 Content 저장 시 개행문자를 <br> 로 변경
        board.setBoardContent(
        	board.getBoardContent().replace("\r\n", "<br>"));
            
        // 조회한 boardNo를 board에 set
        board.setBoardNo(boardNo);
        // title, content, writer, boardNo 담겨있음
        
        // 게시글 DB 등록
        result = boardDAO.insertBoard(board);
    }
    // 3) 이미지(attachment) DB 삽입
    if(result > 0 && !files.isEmpty()) {
    	result = 0; // result 재활용
        
        // files의 데이터를 하나씩 반복 접근하여 DB에 삽입
        for(Attachment at : files) {
        	at.setBoardId(boardNO); // 게시글 번호 set
            result = boardDAO.insertAttachment(at);
            
            if(result == 0) {
            	// 파일삽입 실패시 rollback하기 위해
                // exception 발생
                throw new Exception();
            }
        }
    }
    
    if(result > 0) {
    	// result에 글번호 저장
        result = boardNO;
    }
    result result;
}
        
        

 

BoardDAO

	/** 다음 게시글 번호 조회용 DAO
	 * @return boardNo
	 * @throws Exception
	 */
	public int selectNextNo() throws Exception{
		return sqlSession.selectOne("boardMapper.selectNextNo");
	}


	/** 게시글 삽입용 DAO
	 * @param board
	 * @return result
	 * @throws Exception
	 */
	public int insertBoard(Board board) throws Exception {
		return sqlSession.insert("boardMapper.insertBoard", board);
	}


	/** 파일 삽입용 DAO
	 * @param at
	 * @return result
	 * @throws Exception
	 */
	public int insertAttachment(Attachment at) throws Exception{
		return sqlSession.insert("boardMapper.insertAttachment", at);
	}

board-mapper.xml

	<!-- 다음게시글 번호 조회 -->
	<select id="selectNextNo" resultType="_int">
		SELECT SEQ_BNO.NEXTVAL FROM DUAL
	</select>
	
	<!-- 게시글 삽입 -->
	<insert id="insertBoard" parameterType="Board">
		INSERT INTO BOARD VALUES
		(#{boardNo}, #{boardTitle}, #{boardContent},
		 DEFAULT, DEFAULT, DEFAULT, DEFAULT,
		 #{boardWriter}, #{boardCategory}, 1)
	</insert>
	
	<!-- 파일 삽입 -->
	<insert id="insertAttachment" parameterType="Attachment">
		INSERT INTO ATTACHMENT VALUES
		(SEQ_FID.NEXTVAL, #{boardId},
		#{fileOriginName}, #{fileChangeName}, #{filePath},
		DEFAULT, #{fileLevel}, DEFAULT, DEFAULT)
	</insert>

'study > Spring' 카테고리의 다른 글

11_spring_(★파일수정)  (0) 2020.03.13
10_spring_(파일조회)  (0) 2020.03.12
8_Spring(파일업로드1)  (0) 2020.03.09
7_Spring(페이징)  (0) 2020.02.29
6_Spring(RedirectAttributes, ModelAndView)  (0) 2020.02.28