티스토리 뷰

※ 순서

1. pom.xml에 관련 라이브러리 추가하기

2. root-context.xml에 bean 설정하기

3. mybatis관련 config파일과 쿼리가 작성될 파일 생성하기

4. DB가 연동이 됐는지 테스트 하기

 

1. pom.xml에 관련 라이브러리 추가하기

라이브러리는 <dependencies> </dependencies> 안에 추가해준다.

 

pom.xml

<!-- DB -->

<!-- Maria DB -->

 

<dependency>

     <groupId>org.mariadb.jdbc</groupId>

     <artifactId>mariadb-java-client</artifactId>

     <version>2.0.3</version>

</dependency>

 

<!-- DBCP 데이터베이스 풀 커넥션 -->

<dependency>

     <groupId>commons-dbcp</groupId>

     <artifactId>commons-dbcp</artifactId>

     <version>1.4</version>

</dependency>



<!-- Spring JDBC -->

<dependency>

     <groupId>org.springframework</groupId>

     <artifactId>spring-jdbc</artifactId>

     <version>4.3.9.RELEASE</version>

</dependency>



<!-- Mybatis -->

<dependency>

     <groupId>org.mybatis</groupId>

     <artifactId>mybatis</artifactId>

     <version>3.4.4</version>

</dependency>



<dependency>

     <groupId>org.mybatis</groupId>

     <artifactId>mybatis-spring</artifactId>

     <version>1.3.1</version>

</dependency>

 

2. root-context.xml에 bean 설정하기

sqlSessionFactory의 configLocation은 Mybatis의 config파일의 위치를 지정해준다.

mapperLocation에는 쿼리가 작성될 파일들의 위치를 지정해준다. 아래 설정은 sql폴더 하위의 xml파일을 모두 매핑한다는 의미이다.

 

root-context.xml

<!-- DB -->

   <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">

        <property name="driverClass" value="org.mariadb.jdbc.Driver"></property>

        <property name="url" value="jdbc:mariadb://localhost:3306/데이터베이스명"></property>

        <property name="username" value="아이디"></property>

        <property name="password" value="비밀번호"></property>

    </bean>

 

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

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

        <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"></property>

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

    </bean>

 

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

        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>

    </bean>



 

test.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="sql">
	      <select id="selectDisposableTable" resultType="java.lang.String">
	            SELECT document_srl 
	            FROM `xe_documents` 
	            limit 1
	      </select>
	</mapper>


 

xe를 설치하였기 때문에 xe_documents에서 데이터 1개를 가져오게 해봤다.

 

package com.test.myapp.dao;

public interface SampleDao {
	public String selectSampleData() throws Exception;
}

 

package com.test.myapp.dao;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("sampleDao")
public class SampleDaoImpl implements SampleDao{

	@Autowired
	protected SqlSessionTemplate sqlSession;
	
	@Override
	public String selectSampleData() throws Exception{
		return sqlSession.selectOne("sql.selectDisposableTable");
	}
	
}

 

package com.test.myapp;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.test.myapp.dao.SampleDao;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Resource(name="sampleDao")
	private SampleDao sampleDao;
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public String homeTest(Locale locale, Model model) throws Exception {
		logger.info("Welcome home! The client locale is {}.", locale);
		logger.info("Welcome home! The client locale is {}.", locale);
		logger.debug("dubug test");
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		logger.error("Error Test");
		
		
		String documentSrl=sampleDao.selectSampleData();
		
		model.addAttribute("documentSrl", documentSrl );
		
		return "homeTest";
	}
	
}

 

 

전체구조

참고: https://debugdaldal.tistory.com/130

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함