수업/스프링

[Spring] 7일차

분홍야자 2023. 4. 17. 09:51
@Autowired

 

 

@

쿼리문 라이브러리

 

라이브러리 추가

https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4/1.16

추가

 

root-context.xml 수정

여기부분 주석 두줄 후 밑에 property 추가

<property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property>
<property name="jdbcUrl" value="jdbc:log4jdbc:oracle:thin:@59.0.234.4:1521:xe"></property>

 

 

리소스에 파일 추가

 

파일명

log.jdbc.log4j2.properties

 

log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
  • xml이아닌 파일로 설정방법

 

IMemberDAOTest 가입할 계정 변경하기

실행

콘솔로그에 실행된 쿼리문이 보이게 된다.

 

log4j.xml 수정 및 추가

<!DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd>

<logger name="jdbc.resultset">
		<level value="warn"/>
	</logger>
	
	<logger name="jdbc.connection">
		<level value="warn"/>
	</logger>

	<!-- Root Logger -->
	<root>
		<priority value="warn" />
		<appender-ref ref="console" />
	</root>

 

 

 

 

 

인터페이스 수정 IMemberDAO

 

package com.smart.hrd.persistence;

import com.smart.hrd.domain.MemberDTO;

public interface IMemberDAO {
	
	// 실체가 없는
	// 강제성이 있다.
	public String getTime();
	public void insertMember(MemberDTO mDTO);
	// 회원가입시 id로 user에 대한 정보 가져오기
	public MemberDTO selMember(String userid) throws Exception;
	// 로그인 시 정보 가져오기
	public MemberDTO selLoginInfo(String userid, String userpw) throws Exception;
	
}

 

 

memberMapper.xml 추가

	<!-- 회원가입시 아이디에 대한 정보 가져오기 -->
  <select id="selMember" resultType="com.smart.hrd.domain.MemberDTO">
  	select * 
  	from tbl_member
  	where userid = #{userid}
  </select>
  
  <!-- 로그인 아이디에 대한 정보 가져오기 -->
  <select id="selLoginInfo" resultType="com.smart.hrd.domain.MemberDTO">
  	select * 
  	from tbl_member
  	where userid = #{userid}
  	and userpw = #{userpw}
  </select>

 

MemberDAOImpl 구현체 수정

add해주기

 

알아서 추가됨

 

	@Override
	public MemberDTO selMember(String userid) throws Exception {
		return sqlSession.selectOne(namespace + ".selMember", userid);
	}

	@Override
	public MemberDTO selLoginInfo(String userid, String userpw) throws Exception {
		// 두개의 데이터를 묶어주기 위해 map 사용
		//new HashMap<>() : 다이아몬드 기법  1.6 이상부터 가능
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("userid", userid);
		paramMap.put("userpw", userpw);
		return sqlSession.selectOne(namespace + ".selLoginInfo", paramMap);
	}
  • map 사용하는 게 DTO 생성 보다는 훨씬 편해보인다

 

 

 

 

테이블추가, 인덱스 생성, 프라이머리 키 추가

-- 게시판 테이블 생성
create table tbl_board
(
    bno     NUMBER(10)      NOT NULL,
    title   VARCHAR2(200)   NOT NULL,
    content VARCHAR2(1000)  NULL,
    writer  VARCHAR2(50)    NOT NULL,
    regdate DATE            DEFAULT sysdate,
    viewcnt NUMBER          DEFAULT 0
);

-- 유니크 인덱스 생성
-- 검색 성능을 향상시키기 위해 사용
-- 정보들이 들어가 있다.
-- order by 성능이 많이 떨어진다.
-- index : 정렬되어 있는 정보 
CREATE UNIQUE INDEX idx_tbl_board_PK ON tbl_board(bno ASC);

-- primary key 추가
ALTER TABLE tbl_board
ADD CONSTRAINT tbl_board_bno_PK PRIMARY KEY(bno);

-- 시퀀스
CREATE SEQUENCE board_seq
INCREMENT BY 1
START WITH 1
NOMAXVALUE; -- 끝까지 간다

 

domain 에 클래스(객체) 생성 - BoardDTO

 

package com.smart.hrd.domain;

import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class BoardDTO {
	// Integer 은 null 허용
	private Integer bno;
	private String title;
	private String content;
	private String writer;
	private Date regdate;
	private int viewcnt;
	
}

 

 

DAO 인터페이스 생성 - IBoardDAO

 

  • 추상메소드 만들기

package com.smart.hrd.persistence;

import java.util.List;

import com.smart.hrd.domain.BoardDTO;

public interface IBoardDAO { // 인터페이스
	
	// 글 생성
	public void create(BoardDTO bDto) throws Exception;
	// 글 상세
	public BoardDTO read(Integer bno) throws Exception;
	// 글 수정
	public int update(BoardDTO bDto) throws Exception;
	// 글 삭제
	public int delete(Integer bno) throws Exception;
	// 글 목록 
	public List<BoardDTO> listAll() throws Exception;
	
	
	
}

 

 

게시판 Mapper 생성 - 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">
<!-- namespace="BoardMapper" : 간략화 가능하다. alias 필요없음 -->
<mapper namespace="BoardMapper"> 
	
	<!-- 게시글 등록 -->
	<insert id="create">
		INSERT INTO tbl_board(bno, title, content, writer) 
		VALUES(board_seq.nextval, #{title}, #{content}, #{writer})
	</insert>
	
	<!-- 게시글 상세 -->
	<select id="read" resultType="com.smart.hrd.domain.BoardDTO">
		SELECT bno,
			   title,
			   content,
			   writer,
			   regdate,
			   viewdcnt  
		FROM tbl_board 
		WHERE bno = #{bno}
	</select>
	
	<!-- 게시글 수정 -->
	<update id="update">
		UPDATE tbl_board
		SET title = #{title}, content = #{content}
		WHERE bno = #{bno}
	</update>
	
	<!-- 게시글 삭제 -->
	<delete id="delete">
		DELETE FROM tbl_board
		WHERE bno = #{bno}
	</delete>
	
	<!-- 게시글 목록 -->
	<select id="selectAll" resultType="com.smart.hrd.domain.BoardDTO">
		<!-- 비교연산자가 문자열로 처리되는 경우가 있어 그걸 방지하기 위해 -->
		<![CDATA[
			SELECT bno,
				   title,
				   content,
				   writer,
				   regdate,
				   viewdcnt  
			FROM tbl_board
			WHERE bno > 0
			ORDER BY bno DESC, regdate desc
		]]>
		
	</select>
	
	

</mapper>

 

DAO 구현체 생성

package com.smart.hrd.persistence.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.smart.hrd.domain.BoardDTO;
import com.smart.hrd.persistence.IBoardDAO;

@Repository
public class BoardDAOImpl implements IBoardDAO {

	@Autowired
	private SqlSession session;

	@Override // 추가
	public void create(BoardDTO bDto) throws Exception {
		session.insert("BoardMapper.create", bDto);
	}

	@Override // 상세
	public BoardDTO read(Integer bno) throws Exception {
		return session.selectOne("BoardMapper.read", bno);
	}

	@Override // 수정
	public int update(BoardDTO bDto) throws Exception {
		return session.update("BoardMapper.update", bDto);
	}

	@Override // 삭제
	public int delete(Integer bno) throws Exception {
		return session.delete("BoardMapper.delete", bno);
	}

	@Override // 목록
	public List<BoardDTO> listAll() throws Exception {
		return session.selectList("BoardMapper.listAll");
	}

}

 

 

 

테스트 해보기 - IBoardDAOTest 생성

 

 

 

 

package com.smart.hrd;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.smart.hrd.domain.BoardDTO;
import com.smart.hrd.persistence.IBoardDAO;
import com.smart.hrd.persistence.impl.BoardDAOImpl;

import lombok.extern.log4j.Log4j;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/**/root-context.xml")
@Log4j
public class IBoardDAOTest {

	@Autowired
	private IBoardDAO bDao;
	
	@Test
	public void testCreate() throws Exception {
		BoardDTO bDto = new BoardDTO();
		bDto.setTitle("새로운 글");
		bDto.setContent("새로은 글을 등록합니다");
		bDto.setWriter("user01");
		
		bDao.create(bDto);
		
	}

}

 

	@Test
	public void testUpdate() throws Exception {
		BoardDTO bDto = new BoardDTO();
		bDto.setTitle("수정된 글");
		bDto.setContent("수정된 글입니다");
		bDto.setBno(1);
		
		int result = bDao.update(bDto);
		log.info("result ===> " +  result);
	}