티스토리 뷰
* 현역에 가면 JDBC 는 안 쓰겠지만 마이바티스 등과 같은 라이브러리들은
다 JDBC를 기준으로 만들어진다.
* 마이바티스는 기존의 DAO 계층을 대신한다.
* mapper 에서 구현할 메소드들을 인터페이스에 작성
* mapper 인터페이스는 인터페이스와 완전히 동일한 이름의 xml 파일이 구현한다.
-> xml 파일에 메서드 구현부에 sql문을 작성해놓는듯 보임.
*mybatis 모듈
*mybatis 랑 spring 연결해주는 모듈
위 2개 필요.
(주의! spring-jdbc 라이브러리가 기본적으로 있어야함.)
그리고 나서
SQlSessionFactory (마이바티스 핵심객체) 를 스프링 컨테이너에 빈으로 설정해줘야함.
*root-context.xml 파일의 마이바티스 추가하는 부분.
<!-- 데이터베이스 정보를 주입 -->
<bean id="ds" class="com.zaxxer.hikari.HikariDataSource">
<constructor-arg ref="hikari" />
</bean>
<!-- 마이바티스설정 sqlSessionFactory 빈으로 생성 -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 데이터베이스 정보 전달 -->
<property name="dataSource" ref="ds" />
</bean>
<!-- 마이바티스 관련 어노테이션을 찾아서 설정으로 등록 -->
<mybatis-spring:scan base-package="com.simple.basic.mapper"/>
--------------------------------------------------------------------------------------------------------------------------------
< mybatis 직접 연결해보기 >
*mybatis 모듈들 가져오기.
주의! 기본적으로 spring-jdbc 라이브러리도 있어야함.
- porm.xml mybatis 모듈 추가 부분.
<!-- 스프링 jdbc 모듈 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version> <!-- 스프링 버젼 찾아가지고 맞춰주기 -->
</dependency>
<!-- 마이바티스 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- 마이바티스-스프링 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
maven에서 프로젝트 업데이트 하는거 잊지말기!
*root-context.xml (데이터베이스 관련 설정 파일) 에 설정 추가
- 먼저 Namespaces에서 사용할 모듈 체크
-mabatis의 핵심 객체인 sqlSessionFactory를 빈으로 생성
<!-- 데이터베이스 정보를 주입 -->
<bean id="ds" class="com.zaxxer.hikari.HikariDataSource">
<constructor-arg ref="hikari" />
</bean>
<!-- 마이바티스설정 sqlSessionFactory 빈으로 생성 -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 데이터베이스 정보 전달 -->
<property name="dataSource" ref="ds" />
</bean>
#데이터 베이스가 잘 연결 됬는지 test 해볼 예정.
* 마이바티스 계층 생성
-폴더와 파일 위치 구조
아래와 같이 테스트 영역에 패키지와 파일을 만들었다.
*TestMapper.java 인터페이스 -> 사용할 메서드를 정의
package com.simple.basic.mapper;
public interface TestMapper {
public String getTime(); //1
}
*TestMapper.xml -> 인터페이스의 구현은 완전히 동일한 이름의 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="com.simple.basic.mapper.TestMapper">
<!-- id는 인터페이스의 메서드명 resultType=반환타입 -->
<select id="getTime" resultType="string">
select now()
</select>
</mapper>
- 먼저 구현할 인터페이스의 풀경로를 적는다.
- <select> 태그에서는 메서드를 구현.
id = "메서드명" resultType="반환타입"
<select></select> 태그들 사이에 데이터베이스에 적용할 쿼리문을 적는다. ( 위에서의 예시로는 select now() )
★ 현재 마이바티스 계층에서 xml 파일(인터페이스 구현)이 인터페이스의 경로는 알지만
마이바티스에서 xml 파일을 읽어내지 못 하는 상태.
root-context.xml ( 데이터베이스 설정) 파일에서 Mapper.xml 파일을 읽어낼 수 있도록 설정해주어야 한다. 바로 go!
<!-- 마이바티스 관련 어노테이션을 찾아서 설정으로 등록 -->
<mybatis-spring:scan base-package="com.simple.basic.mapper"/>
root-context.xml 파일 전체 모습
<?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"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
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">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- 데이터베이스 정보는 외부 파일로 관리 -->
<!-- classpath:/ 자바/리소스 경로를 가르킵니다 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"
value="classpath:/DB-config/hikari.properties" /> <!-- classpath:/ 이게 붙었다는 의미는 -->
</bean>
<!-- 데이터베이스 mysql로 설정 -->
<bean id="hikari" class="com.zaxxer.hikari.HikariConfig">
<property name="driverClassName"
value="${ds.driverClassName}" />
<property name="jdbcUrl" value="${ds.jdbcUrl}" />
<property name="username" value="${ds.username}" />
<property name="password" value="${ds.password}" />
</bean>
<!-- 데이터베이스 오라클로 설정 -->
<!-- <bean id="hikari" class="com.zaxxer.hikari.HikariConfig"> <property
name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property
name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" /> <property name="username"
value="jsp" /> <property name="password" value="jsp" /> </bean> -->
<!-- 데이터베이스 정보를 주입 -->
<bean id="ds" class="com.zaxxer.hikari.HikariDataSource">
<constructor-arg ref="hikari" />
</bean>
<!-- 마이바티스설정 sqlSessionFactory 빈으로 생성 -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 데이터베이스 정보 전달 -->
<property name="dataSource" ref="ds" />
</bean>
<!-- 마이바티스 관련 어노테이션을 찾아서 설정으로 등록 -->
<mybatis-spring:scan base-package="com.simple.basic.mapper"/>
</beans>
# 마이바티스가 잘 연결되었는지 테스트 해보기
JDBCMybatis.java 파일
package com.simple.basic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.simple.basic.mapper.TestMapper;
@RunWith(SpringJUnit4ClassRunner.class)//junit으로 테스트환경을 구성
@ContextConfiguration("file:src/main/webapp/WEB-INF/config/root-context.xml")//동작시킬 스프링 설정파일
public class JDBCMybatis {
@Autowired
SqlSessionFactoryBean sqlSessionFactory;
@Autowired
TestMapper testMapper;
@Test
public void testCode01() {
//마이바티스 핵심 객체
System.out.println(sqlSessionFactory);
}
@Test
public void testCode02() {
String time = testMapper.getTime();
System.out.println(time);
}
}
테스트 실행 ( 실행하는 법 리마인드)
테스트 실행 결과
연결이 잘 되었음을 확인하였다.
참 쉽죠 ?
#추가 - 설정 파일들 모습들
porm.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 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.simple</groupId>
<artifactId>basic</artifactId>
<name>SpringBasic</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<!-- 컨택스트 패스 변경 - artifactId를 변경, 톰캣의 module에서 변경 -->
<!-- pom.xml에서 사용할 변수들 -->
<!-- 자바버전 11, 스프링버전 변경 -->
<properties>
<java-version>11</java-version>
<org.springframework-version>5.0.7.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<!--필요한 라이브러리들 -->
<dependencies>
<!-- 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>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<!-- 서블릿 버전 최소 3.1이상으로 변경 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 오라클 커넥터 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>21.1.0.0</version>
</dependency>
<!-- ㅡmysql 커넥터 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<!-- 스프링 jdbc 모듈 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version> <!-- 스프링 버젼 찾아가지고 맞춰주기 -->
</dependency>
<!-- 히카리 커넥션 풀 -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.3.1</version>
</dependency>
<!-- 테스트환경 - spring-test모듈 and junit기능 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version> <!-- 스프링 버젼 찾아가지고 맞춰주기 -->
<scope>test</scope>
</dependency>
<!-- Test 버젼은 최소 4.12이상 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 마이바티스 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- 마이바티스-스프링 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>
<!-- maven 관련 설정이 들어가는 곳 bulid -->
<!-- 메이븐 설정 - 메이븐 버전 3.8.1 변경, 컴파일 자바 레벨 11 -->
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<!-- 요기 !!!!!!!!!!!!!!!!!!!!!!!!!!! -->
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</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>
web.xml
<?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 https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 스프링 전역 설정파일 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/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>
<!-- 디스패쳐 서블릿 등록 -->
<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/config/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>
<!-- 스프링에서 제공하는 인코딩필터 등록 -->
<filter>
<filter-name>encodingFilter</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>
<!-- 위에 지정한 encodingFilter이름을 모든 패턴에 적용 -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
'자바 Spring' 카테고리의 다른 글
- Total
- Today
- Yesterday
- 알람 시계 문제
- 조건문
- 배열의 정렬
- 배열 삭제
- output 스트림
- FOR문
- interface #자바
- 자바 api
- 중앙정보처리학원
- 자바
- 박문석 선생님
- 배열과 탐색
- 자바스크립트 ES6 문법
- api 활용
- 강남 중앙정보처리학원
- 자바수업
- nasted class
- 자바#자바수강기록
- 국비학원
- 내포 클래스
- JS ES6 문법
- input 스트림
- 가비지 콜렉팅
- 국비학원 수업
- 다중 반복문
- 국비지원 학원 수업 내용
- 박인욱 강사님
- 데이터베이스 수업
- 강남역 12번 춣구
- 오코노라멘
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |