Back-end/Spring

Spring) DB연결 방법 3가지(직접, Bean객체, MyBatis)

luana_eun 2022. 4. 25. 15:30
728x90

1. 클래스에서 직접 연결하는 방법. 

public class DBConnectTest {

	private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
	private static final String DBURL = "jdbc:mysql://localhost:3306/springdb";
	private static final String DBID = "root";
	private static final String DBPW = "1234";
	
	
	@Test
	public void 디비연결테스트() {
		try(Connection con = DriverManager.getConnection(DBURL, DBID, DBPW)) {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}	

	}
}

 


2. 빈 객체를 생성해서 불러오는 방법

root-context.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName">
		<value>com.mysql.cj.jdbc.Driver</value>
	</property>
	<property name="url" value="jdbc:mysql://localhost:3306/springdb"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1234"></property>
</bean>

src/test/java/DataSourceTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
		locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"}
		)
public class DataSourceTest {
	// DataSource Bean(객체)를 사용해서 DB연결 테스트하기. 
	
	// 1. 디비 연결 객체 생성
	@Inject
	private DataSource ds; 
	
	
	// 2. 주입된 객체가 있는지 체크 테스트.
	@Test
	public void DataSource객체확인테스트() {
		System.out.println("ds확인 : " + ds);
	}
	
	
	// 3. 디비 연결 테스트
	@Test
	public void Bean으로디비연결테스트() {
		try {
			Connection con = ds.getConnection();
			System.out.println("Bean으로 디비연결 확인 : " + con);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

 

 

** 실행한 콘솔창을 확인해보자 **

INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper

            - Loaded default TestExecutionListener class names from location .....

 

INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper

            - Using TestExecutionListeners: ...

 

INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader 

         - Loading XML bean definitions from URL [file:src/main/webapp/WEB-INF/spring/root-context.xml]

        => 위에서 적어준 파일을 불러온다. 

 

INFO : org.springframework.context.support.GenericApplicationContext 

         - Refreshing org.springframework.context.support.GenericApplicationContext@2758fe70:

           startup date [Mon Apr 25 11:06:03 KST 2022]; root of context hierarchy

         => root context를 실행한다는 의미. 

 

INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor 

          - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring

         =>  'javax.inject.Inject' 어노테이션이 발견됐고, 빈과 자동으로 연결시킨다.(autowiring)

 

INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.cj.jdbc.Driver

           => DriverManagerDataSource 객체가 실행이 되고, JDBC 드라이버를 부른다. 

 

ds확인 : org.springframework.jdbc.datasource.DriverManagerDataSource@27f981c6

 

INFO : org.springframework.context.support.....(생략) - Closing ....(생략)... root of context hierarchy

 

 


3.  MyBatis config DTD 사용.

1) MyBatis를 사용해서 DB에 연결하려면 SqlSessionFactory가 있어야한다. 

2) src/main/resource/mybatis-config.xml 파일 생성.

   MyBatis가 실행될때 필요한 설정들을 명시해 놓는 파일. MyBatis객체가 생성될때 이 파일이 실행된다.  

3)  mybatis-config.xml에 DTD 설정.

   mybatic홈페이지에서(https://mybatis.org/mybatis-3/ko/getting-started.html) 해당 부분의 코드를 복사한다.

4) root-context.xml 에 객체 생성.

root-context.xml

객체를 가져올때는 property value="" 가 아닌 property ref=""로 가져온다. 

configLocation : 설정 파일의 위치.

 classpath : src/main/resource

<!-- SqlSessionFactory 객체 생성 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation" value="classpath:/mybatis-config.xml" />
</bean>

5) 연결 테스트 코드 작성

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
		locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"}
		)
public class MyBatisTest {
	@Inject
	private SqlSessionFactory sqlFactory;
	
	@Test
	public void SqlSessionFactory객체확인() {
		System.out.println("Factory객체 확인" + sqlFactory);
	}
	
	@Test
	public void MyBatis로DB연결확인() {
		SqlSession session = sqlFactory.openSession();
		System.out.println("DB연결 세션: " + session);
	}
}

 

 


4. DB로그 간단하게 출력하기(log4jdbc사용)(선택)

Maven홈페이지에 들어가서 Log4JDBC를 검색해서 들어간다. 

https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4.1

현재 제일 최신버전인 1.6을 선택하고

Maven코드를 다운받아서 pom.xml의 <dependencies>에 추가한다. 

 

추가로 root-context.xml에서 dataSource 설정을 변경해야한다. 

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName">
		<!--변경전: com.mysql.cj.jdbc.Driver -->
		<value>net.sf.log4jdbc.sql.jdbcapi.DriverSpy</value>
	</property>
    <!--변경전: name="url" value="jdbc:mysql://localhost:3306/springdb -->
	<property name="url" value="jdbc:log4jdbc:mysql://localhost:3306/springdb"></property>
</bean>

 

마지막으로 src/main/resource 패키지 밑에 아래의 설정파일 두개를 추가한다. 

log4jdbc.log4j2.properties
0.00MB
logback.xml
0.00MB

 

결과: 이전과 다르게 콘솔레 DB로그가 세세히 찍힌다.

728x90