본문 바로가기
DB

Spring 프로젝트에 Mysql DB 연동하는 방법

by sliora 2017. 3. 10.

Spring Project에 설정파일 3개를 수정해야 합니다.( root-context.xml , pom.xml , web.xml )




1. root-context.xml (root로 되어있는곳에 사용할 id와 password를 입력해야 합니다.)

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql://localhost:3306/DB이름?characterEncoding=UTF8" />

<property name="username" value="root"/>

<property name="password" value="root"/>

</bean>


<!-- 만약 Log4J가 연동된 모듈로 MySQL 연결 설정을 원하면 --->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
<property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"/> 
    <property name="url"  
     value="jdbc:log4jdbc:mysql://localhost:3306/DB명?characterEncoding=UTF8&amp;useSSL=false"/> 
<property name="username" value="root" /> 
<property name="password" value="root" /> 
</bean>


1-1. sqlSessionFactory를 넣어주고, mapper 경로를 지정해줍니다.

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="mapperLocations" value="classpath:/**/*.xml" />

</bean>


1-2. SqlSession을 구현하고 코드에서 SqlSession를 대체하는 역할을 하는 MyBatis 연동 모듈을 추가해준다. 

<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">

<constructor-arg index="0" ref="sqlSessionFactory" />

</bean>




2. pom.xml (메이븐 설정)

<!-- MySQL JDBC 라이브러리 설정 --> 
<dependency> 
<groupId>mysql</groupId> 
<artifactId>mysql-connector-java</artifactId> 
<version>5.1.39</version> 
</dependency> 

<!-- Spring-JDBC 연동 라이브러리 --> 
<dependency> 
<groupId>org.springframework</groupId> 
<artifactId>spring-jdbc</artifactId> 
<version>4.3.1.RELEASE</version> 
</dependency> 

<!-- MyBatis --> 
<dependency> 
<groupId>org.mybatis</groupId> 
<artifactId>mybatis</artifactId> 
<version>3.4.1</version> 
</dependency> 

<!-- Spring-MyBatis 연동 라이브러리 --> 
<dependency> 
<groupId>org.mybatis</groupId> 
<artifactId>mybatis-spring</artifactId> 
<version>1.3.0</version> 
</dependency> 

<!-- JDBC Log4j 연동 모듈 --> 
<dependency> 
<groupId>org.bgee.log4jdbc-log4j2</groupId> 
<artifactId>log4jdbc-log4j2-jdbc4</artifactId> 
<version>1.16</version> 
</dependency>


3. web.xml (Servlet맵핑을 위한 설정)

<servlet-mapping>

<servlet-name>appServlet</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>