[Spring] MVC + Maven project 생성 및 실행2 (MyBatis, MySql)

sua_ahn·2023년 2월 27일
0

Spring

목록 보기
4/8
post-thumbnail

MyBatis

: SQL 매핑 프레임워크

→ JDBC 코드의 복잡한 작업을 단축시킴

특징

  • SQL 쿼리문을 코드 내에서 쓰지 않고 Mapper 파일에서 관리함으로써,
    코드와 SQL 쿼리문을 분리
  • 자동으로 Connection close() 기능
  • MyBatis 내부적으로 PreparedStatement 처리
  • #{prop}와 같이 속성을 지정하면 내부적으로 자동 처리
  • 리턴 타입을 지정하는 경우, 자동으로 객체 생성 및 ResultSet 처리

 

 


1. 의존성 추가

: DB연동에 필요한 라이브러리 의존 설정 추가

  • mybatis
  • mybatis-spring
  • spring-jdbc
  • spring-orm
  • mysql-connector-java
  • commons-dbcp2 (톰캣에서 커넥션풀을 이용하기 위한 라이브러리)
  • commons-pool2

pom.xml

<!-- mybatis 사용 시 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.3</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.3</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.25</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.3.25</version>
</dependency>

<!-- mysql 사용시 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.29</version>
</dependency>


<!-- DBCP : DB Connection Pool 사용 -->
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-dbcp2</artifactId>
	<version>2.8.0</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.8.0</version>
</dependency>

 

2. properties & xml 설정

jdbc.properties

: MySql 설정

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb?serverTimeZone=Asia/Seoul
jdbc.username=root
jdbc.password=0000
jdbc.initialSize=5
jdbc.maxActive=20

applicationContext.xml

  1. 위 properties 파일을 읽어와서 dataSource 속성 설정

  2. MyBatis의 핵심 객체인 SQLSessionFactory는 내부적으로 SQLSession을 통해 Connection을 생성하여 원하는 SQL을 전달하고, 결과를 리턴받음

<?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: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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- DB 설정파일 로딩 -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:properties/jdbc.properties</value>
			</list>
		</property>
	</bean>
    
	<!-- DBMS 설정 (db서버 대기시간 최대 3초) -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		<property name="initialSize" value="${jdbc.initialSize}"/>
		<property name="maxActive" value="${jdbc.maxActive}"/>
		<property name="minIdle" value="${jdbc.initialSize}"/>
		<property name="maxWait" value="3000"/>
		<property name="poolPreparedStatements" value="true"/>
		<property name="maxOpenPreparedStatements" value="50"/>
	</bean>
    
	<!-- MyBatis 설정 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="mapperLocations" value="classpath:sqls/*.xml"/>
	</bean>
    
	<!-- sqlSession 취득 (생성자에 인자 넣기) -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory"/>
		<constructor-arg index="1" value="SIMPLE"/>
	</bean>
    
	<!-- jdbc 설정 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
</beans>

web.xml

  1. 위에서 생성한 applicationContext.xml 설정파일의 위치 등록

  2. ContextLoaderListener는 web.xml에 설정파일들이 모두 load 되도록 등록할때 사용 (위치 미지정시 root-context.xml로)

    <web-app> 태그 안에 추가

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 

 

3. mapper 생성

Mapper : SQL과 그에 대한 처리를 지정하는 역할

mapper.xml

: MyBais 규칙에 따라 태그 내에 쿼리문 작성

<?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="Bbs">
	<select id="getBbs" parameterType="Integer" resultType="com.mypack.sample.dto.BbsDto">
		select * from bbs
		where seq=#{seq}
	</select>
    
    <insert id="writeBbs" parameterType="com.mypack.sample.dto.BbsDto">
		insert into bbs(id, ref, step, depth, title, content, wdate, del, readcount)
		values(#{id}, (select ifnull(max(ref), 0)+1 from bbs b), 0, 0, 
			#{title}, #{content}, now(), 0, 0)
	</insert>
</mapper>
  • namespace 속성 : mapper를 구분하는 식별자
  • 타입 속성 : 클래스 경로 작성 (wrapper class는 경로 생략 가능)
  • 파라미터 : #{문자열}, ${정수}
  • 조건문 사용 가능 : <if test="조건식">쿼리문</if>

 

4. Repository 생성

DB와 연동될 DAO 인터페이스 및 클래스

@Repository
public class BbsDaoImpl implements BbsDao {
	
	@Autowired
	SqlSession session;
	
	String ns = "Bbs.";

	@Override
	public BbsDto getBbs(int seq) {
		return session.selectOne(ns + "getBbs", seq);
	}
}

 

5. Service 생성

@Service
public class BbsServiceImpl implements BbsService {
	
	@Autowired
	BbsDao dao;

	@Override
	public BbsDto getBbs(int seq) {
		return dao.getBbs(seq);
	}
}

 

6. Controller 생성

@Controller
public class BbsController {
	
	@Autowired
	BbsService service;
    
    // @GetMapping(value = "bbsdetail.do")
	@RequestMapping(value = "bbsdetail.do", method = RequestMethod.GET)
	public String bbsdetail(Model model, int seq) {
    
		BbsDto dto = service.getBbs(seq);
        
		model.addAttribute("bbsdto", dto);
        
		return "bbsdetail";
	}

Controller ⇄ Service ⇄ Dao ⇄ Mapper

profile
해보자구

0개의 댓글