실습
1. src/main/resource/application.properties
#server port
server.port=10001
##JDBC datasource
#spring.datasource.hikari.driver-class-name=oracle.jdbc.OracleDriver
#spring.datasource.hikari.jdbc-url=jdbc:oracle:thin:@//localhost:1521/XE
#spring.datasource.hikari.username=hr
#spring.datasource.hikari.password=hr
#JDBC spy datasource
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
spring.datasource.hikari.driver-class-name=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
spring.datasource.hikari.jdbc-url=jdbc:log4jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.hikari.username=hr
spring.datasource.hikari.password=hr
#log level
logging.level.root=info
2. src/main/java/com.example.ex01/myBatis/MyBatisConfig.java
package com.example.ex01.myBatis;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@Configuration //설정 관련 클래스에 작성한다.
@MapperScan("com.example.ex01.mapper") //작성한 경로부터 하위 경로까지 모두 @Mapper를 스캔한다.
@RequiredArgsConstructor
public class MyBatisConfig {
// 커넥션 풀 및 MyBatis에 필요한 요소를 메모리에 할당 및 관리, xml과 java연동에 필요한 경로 관리
private final ApplicationContext applicationContext;
// @Bean : 메소드의 리턴 객체를 스프링 컨테이너에 등록, 객체명은 메소드의 이름으로 자동 설정되며,
// 직접 설정하고자 할 때에는 @Bean(name="객체명")으로 사용
@Bean //@Configuration 또는 @Component가 작성된 클래스의 메소드에만 사용이 가능하다.
@ConfigurationProperties(prefix = "spring.datasource.hikari") //properties 파일에서 prefix인 설정 모두 가져오기
public HikariConfig hikariConfig() {
return new HikariConfig(); //properties파일에서 가져온 설정들과 필드가 매핑되어 자동으로 주입된다.
}
@Bean
public HikariDataSource hikariDataSource(){
// DataSource 객체에 DBMS 정보 설정
return new HikariDataSource(hikariConfig());
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws IOException {
// 세션 팩토리 설정 객체
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// DBMS 정보를 담고 있는 DataSource를 세션 팩토리 설정 객체에 전달
sqlSessionFactoryBean.setDataSource(hikariDataSource());
// SQL 쿼리를 작성할 mapper.xml 경로 설정
sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath*:/mapper/*.xml"));
try {
// 위에서 설정한 세션 팩토리 빈을 통해 세션 팩토리 생성
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
// 팟홀(언더바) 표기법을 카멜 표기법으로 자동 변경 설정
sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
return sqlSessionFactory;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3. src/test/java/com.example.ex01/myBatis/MyBatisConfigTests.java
package com.example.ex01.myBatis;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
@SpringBootTest
@Slf4j
public class MyBatisConfigTests {
@Autowired
private DataSource dataSource;
@Autowired
private SqlSessionFactory sqlSessionFactory;
// @Test
// public void dataSourceTest(){
//// try statement 문법
//// try(외부 드라이버 요청 문법 작성){}
//// try문에 있는 소괄호에 연결객체를 요청하면, 사용종료 후 자동으로 close()된다.
// try
// (
// Connection conn = dataSource.getConnection();
// )
// {
// log.info("---------------------------------");
// log.info("datasource connection : " + conn);
// log.info("---------------------------------");
//
// } catch (Exception e){
// e.printStackTrace();
// }
// }
@Test
public void sqlSessionTest(){
log.info("-------------------------------");
log.info("sql session factory : " + sqlSessionFactory);
log.info("-------------------------------");
try
(
SqlSession sqlSession = sqlSessionFactory.openSession(true);
Connection conn = sqlSession.getConnection();
)
{
log.info("sql session : " + sqlSession);
log.info("-------------------------------");
log.info("sql session connection " + conn);
log.info("-------------------------------");
}catch (Exception e){
e.printStackTrace();
}
}
}
4. src/main/java/com.example.ex01/mapper/TimeMapper.java
package com.example.ex01.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper //스프링 마이바티스에서 xml파일과 연결될 Mapper 인터페이스임을 알려준다.
public interface TimeMapper {
// SQL이 복잡하거나 길어지는 경우에는 어노테이션보다 XML방식을 더 선호하게 된다.
// @Select("SELECT SYSDATE FROM DUAL")
public String getTime();
}
5. src/test/java/com.example.ex01/mapper/TimeMapperTests.java
package com.example.ex01.mapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Slf4j
public class TimeMapperTests {
@Autowired
private TimeMapper timeMapper;
@Test
public void getTimeTest(){
log.info("-------------------------------");
log.info(timeMapper.getTime());
log.info("-------------------------------");
}
}
6. src/main/resource/mapper/TimeMapper.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.example.ex01.mapper.TimeMapper">
<select id="getTime" resultType="string">
SELECT SYSDATE FROM DUAL
</select>
</mapper>
7. pom.xml
- build 태그 안에 코드 추가
<?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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>ex01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ex01</name>
<description>MyBatis Practice</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.setting</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>