본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

JAVA/Spring

MyBatis: 간단히 DB 연결테스트하기

앞서 JDBC 드라이버와 template을 통해 DB연결을 테스트해봤다.

https://standout.tistory.com/1109

 

JDBC 드라이버: 간단히 DB 연결테스트하기

간단히 JDBC DB연결테스트를 해보자. pom.xml에 jdbc 라이브러리를 추가하고, Controller class에 JDBC 드라이버를 로드해 테스트한다. org.mariadb.jdbc mariadb-java-client 3.1.4 // JDBC 드라이버 로드 Class.forName("org.ma

standout.tistory.com

https://standout.tistory.com/1110

 

JdbcTemplate: 간단히 DB 연결테스트하기

앞서 전통적인 방법인 JDBC 드라이버로 간단히 DB연결 테스트를 해봤다. https://standout.tistory.com/1109

standout.tistory.com

 

 

 

MyBatis 라이브러리를 추가해줍시다.

<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.10</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.7</version>
		</dependency>
		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
			<version>3.0.7</version>
		</dependency>

더보기
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Board_hardCoding</groupId>
	<artifactId>Board_hardCoding</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<!-- spring context, web, MVC는 세트로 같은 버전을 사용해야한다. -->
		<org.springframework-version>5.3.23</org.springframework-version>
	</properties>

	<!-- dependencies 위치 -->
	<dependencies>

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

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

		<!-- Spring Core 및 JDBC 의존성 추가 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
			<version>3.1.4</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.10</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.7</version>
		</dependency>
		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
			<version>3.0.7</version>
		</dependency>

	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<release>11</release>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

 

applicationContext,xml에 sqlsession을 추가하되, mybatis설정 + sql이 보관될 영역을 지정한다.

<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>

더보기
<?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:mvc="http://www.springframework.org/schema/mvc"
	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/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- resources location설정 -->
	<mvc:resources mapping="/resources/**"
		location="/resources/" />

	<!-- Spring MVC의 애노테이션 기반 컨트롤러를 활성화합니다. -->
	<mvc:annotation-driven />

	<!-- 컴포넌트 스캔을 통해 지정된 패키지에서 빈으로 등록할 클래스를 찾습니다. -->
	<context:component-scan
		base-package="com.sanghee.board" />

	<!-- ViewResolver -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 외부 properties 파일을 로드하는 PropertyPlaceholderConfigurer 설정 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location"
			value="/WEB-INF/config/jdbc.properties" />
	</bean>

	<!-- 데이터베이스 설정 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="${spring.datasource.driverClassName}" />
		<property name="url" value="${spring.datasource.url}" />
		<property name="username"
			value="${spring.datasource.username}" />
		<property name="password"
			value="${spring.datasource.password}" />
	</bean>

	<!-- JdbcTemplate 설정 -->
	<bean id="jdbcTemplate"
		class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</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>


</beans>

+ 아래게시물을 참고하여 파일이 잘 위치했는지 확인 할 수 있다.

https://standout.tistory.com/1111

 

classpath상 파일 존재여부 확인하기

classpath는 보통 프로젝트의 src디렉토리 혹은 WEB-INF/classes 등을 가르킨다. classpath:// 경로에 파일이 잘 읽히는지 확인하고싶다면 아래의 코드를 이용하자. ClassLoader classLoader = getClass().getClassLoader();

standout.tistory.com

 

 

 

추후 VO등을 정의하기 위해 사용될 mybatis-config.xml를 만들고, 실제 동작할 sql이 든 test.xml를 생성해 간단히 작성해보자. 이때 실행될 sql은 미리 db 쿼리를 실행해 확인해보면 좋겠다.

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
</configuration>
<?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.sanghee.board">
	<select id="count" resultType="Integer"
		parameterType="String">
		SELECT COUNT(*) FROM Board;
	</select>
</mapper>

 

 

 

 

sqlsession을 사용해 간단히 실행해보자.

import org.apache.ibatis.session.SqlSession;
	
	@Autowired
	private SqlSession SqlSession;
System.out.println((Object)SqlSession.selectOne("com.sanghee.board.count"));

더보기
package com.sanghee.board.controller;

import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.ibatis.session.SqlSession;

@Controller
public class BoardController {

	private final JdbcTemplate jdbcTemplate;
	
	@Autowired
	private SqlSession SqlSession;

	@Autowired
	public BoardController(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@RequestMapping(value = { "/", "/board/list.do" })
	public String list() throws ClassNotFoundException {

		// JDBC 드라이버 로드
		// JDBC를 직접 사용하여 연결을 시도하고 예외 처리를 통해 연결 상태를 확인하는 전통적인 방법
//		Class.forName("org.mariadb.jdbc.Driver");
//		String jdbcUrl = "jdbc:mariadb://127.0.0.1:example/example";
//        String username = "example";
//        String password = "example";
//
//        try {
//            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
//            System.out.println("연결 성공!");
//            connection.close();
//        } catch (SQLException e) {
//            System.out.println("연결 실패: " + e.getMessage());
//        }

		// Spring의 JdbcTemplate을 사용하여 연결을 시도하고, Spring이 예외 처리를 대신 수행하도록 하는 방법
		try {
			// 데이터베이스 연결 상태를 확인하기 위해 쿼리를 실행하지 않고도 연결을 체크할 수 있습니다.
			jdbcTemplate.getDataSource().getConnection();
			System.out.println("Database connection successful!");
		} catch (Exception e) {
			System.out.println("Database connection failed: " + e.getMessage());
		}
		
		
		ClassLoader classLoader = getClass().getClassLoader();
		
		// 클래스패스 상의 리소스의 경로를 지정하여 읽습니다.
		InputStream resourceStream = classLoader.getResourceAsStream("mybatis/mybatis-config.xml");
		if (resourceStream != null) {
		    System.out.println("mybatis/mybatis-config.xml 파일이 클래스패스 상에 존재합니다.");
		} else {
		    System.out.println("mybatis/mybatis-config.xml 파일을 클래스패스에서 찾을 수 없습니다.");
		}
		
		System.out.println((Object)SqlSession.selectOne("com.sanghee.board.count"));


		return "/board/list";
	}

	@RequestMapping(value = { "/board/sub.do" })
	public String sub() {
		return "/board/sub";
	}

}

 

 

완료.