Web/Spring

MyBatis-Spring

당진개발자 2024. 4. 22. 14:25

1. MyBatis

 


 

2. MyBatis-Spring

 


 

3. 코드 예제

  1) pom.xml에 라이브러리 추가

<!-- MySql & MyBatis -->
		<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<version>${com.mysql-version}</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${org.mybatis-version}</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${org.mybatis-spring-version}</version>
		</dependency>

 

  2) root-context.xml 작성

    - dataSource : DB Connection Pool 설정, context.xml에 설정 파일 존재

    - sqlSessionFactoryBean : sqlSessionFactoryBean 설정, alias 설정, mapper 경로 설정

<?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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://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
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<context:component-scan base-package="com.ssafy.*.model,com.ssafy.util,com.ssafy.board.aop"/>
	
	<aop:aspectj-autoproxy/>
	
	<!-- <bean id="ds" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
		<property name="url" 
			value="jdbc:mysql://127.0.0.1:3306/ssafyweb?serverTimezone=UTC&amp;useUniCode=yes&amp;characterEncoding=UTF-8"/>
		<property name="username" value="ssafy"/>
		<property name="password" value="ssafy"/>
	</bean> -->
	
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="java:comp/env/jdbc/ssafy"></property>
	</bean>
	
	<!-- <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="configLocation" value="classpath:mybatis-config.xml"/>
		<property name="mapperLocations">
			<list>
				<value>classpath:mapper/member.xml</value>
				<value>classpath:mapper/board.xml</value>
			</list>
		</property>
	</bean> -->
	
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="typeAliasesPackage" value="com.ssafy.*.model"/>
		<property name="mapperLocations" value="classpath:mapper/*.xml"/>
	</bean>
	
	<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactoryBean"></constructor-arg>
	</bean> -->
	
	<!-- <bean id="boardMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.ssafy.board.model.mapper.BoardMapper"/>
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
	</bean> -->
	
	<!-- mybatis에서 제공하는 scan 태그를 통해 repository(Mapper) interface들의 위치를 지정. -->
	<mybatis-spring:scan base-package="com.ssafy.*.model.mapper"/>
	
    <!-- 트랜잭션 관리자 설정 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
    <!-- 어노테이션 기반 트랜잭션 설정 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
		
</beans>

 

  3) BoardMapper.java

package com.ssafy.board.model.mapper;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Mapper;

import com.ssafy.board.model.BoardDto;
import com.ssafy.board.model.FileInfoDto;

@Mapper
public interface BoardMapper {

	void writeArticle(BoardDto boardDto) throws SQLException;

	void registerFile(BoardDto boardDto) throws Exception;

	List<BoardDto> listArticle(Map<String, Object> param) throws SQLException;

	int getTotalArticleCount(Map<String, Object> param) throws SQLException;

	BoardDto getArticle(int articleNo) throws SQLException;

	void updateHit(int articleNo) throws SQLException;

	void modifyArticle(BoardDto boardDto) throws SQLException;

	void deleteFile(int articleNo) throws Exception;

	void deleteArticle(int articleNo) throws SQLException;

	List<FileInfoDto> fileInfoList(int articleNo) throws Exception;

}

 

  4) board.xml

    - namespace는 mapper 인터페이스의 full name을 작성

    - sql id는 인터페이스의 메서드 명으로 작성

<?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="com.ssafy.board.model.mapper.BoardMapper">

	<resultMap type="boardDto" id="article">
		<result column="article_no" property="articleNo"/>
		<result column="user_id" property="userId"/>
		<result column="user_name" property="userName"/>
		<result column="subject" property="subject"/>
		<result column="content" property="content"/>
		<result column="hit" property="hit"/>
		<result column="register_time" property="registerTime"/>
	</resultMap>
	
	<resultMap type="boardDto" id="viewArticle" extends="article">
		<collection property="fileInfos" column="article_no" javaType="list" ofType="fileInfoDto" select="fileInfoList"/>
	</resultMap>
	
	<resultMap type="fileInfoDto" id="file">
		<result column="save_folder" property="saveFolder"/>
		<result column="original_file" property="originalFile"/>
		<result column="save_file" property="saveFile"/>
	</resultMap>

	<insert id="writeArticle" parameterType="boardDto">
		insert into board (user_id, subject, content, hit, register_time)
		values (#{userId}, #{subject}, #{content}, 0, now())
		<selectKey resultType="int" keyProperty="articleNo" order="AFTER">
			select last_insert_id()
		</selectKey>
	</insert>
	
	<insert id="registerFile" parameterType="boardDto">
		insert into file_info (article_no, save_folder, original_file, save_file)
		values
		<foreach collection="fileInfos" item="fileinfo" separator=" , ">
			(#{articleNo}, #{fileinfo.saveFolder}, #{fileinfo.originalFile}, #{fileinfo.saveFile})
		</foreach>
	</insert>

	<sql id="search">
		<if test="word != null and word != ''">
			<if test="key == 'subject'">
				and subject like concat('%', #{word}, '%')
			</if>
			<if test="key != 'subject'">
				and ${key} = #{word}
			</if>
		</if>
	</sql>

	<select id="listArticle" parameterType="map" resultMap="article">
		select b.article_no, b.user_id, b.subject, b.content, b.hit, b.register_time, m.user_name
		from board b, members m 
		where b.user_id = m.user_id
		<include refid="search"></include>
		order by b.article_no desc
		limit #{start}, #{listsize}
	</select>
	
	<select id="getTotalArticleCount" parameterType="map" resultType="int">
		select count(article_no)
		from board
		<where>
			<include refid="search"></include>
		</where>
	</select>
	
	<select id="getArticle" parameterType="int" resultMap="viewArticle">
		select b.article_no, b.user_id, b.subject, b.content, b.hit, b.register_time, m.user_name 
		from board b, members m
		where b.user_id = m.user_id
		and b.article_no = #{articleNo}
	</select>
	
	<select id="fileInfoList" resultMap="file">
		select save_folder, original_file, save_file
		from file_info
		where article_no = #{articleNo}
	</select>
	
	<update id="updateHit" parameterType="int">
		update board
		set hit = hit + 1
		where article_no = #{articleNo}
	</update>
	
	<update id="modifyArticle" parameterType="boardDto">
		update board
		set subject = #{subject}, content = #{content}
		where article_no = #{articleNo}
	</update>
	
	<delete id="deleteFile" parameterType="int">
		delete from file_info
		where article_no = #{articleNo}
	</delete>
	
	<delete id="deleteArticle" parameterType="int">
		delete from board
		where article_no = #{articleNo}
	</delete>

</mapper>