kimmgamjja

[Java] Spring 에서 DB 연결 본문

공부/Java

[Java] Spring 에서 DB 연결

인절미댕댕이 2025. 2. 28. 15:36
728x90

* mysql 사용함

 

Spring 프레임워크에서 MySQL 데이터베이스 연결시 

dataSource Bean
sqlSessionFactory Bean
MapperScannerConfigurer Bean
transactionManager Bean
txAdvice Bean
AOP Configuration
tx:annotation-driven

 

이러한 설정을 해줘야한다.

 

(이것들 외에 개인적으로 필요한 설정이 있다면 따로 추가해주면된다)

 

이 설정들을 통해 데이터소스와 MyBatis를 사용하여 데이터베이스에 연결한다

 

<?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:c="http://www.springframework.org/schema/c" xmlns:context="http://www.springframework.org/schema/context"
   xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
 
 	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://2.2.2.2:3306/BASE_DB?useSSL=false"/>
		<property name="username" value="test"/>
		<property name="password" value="test123"/>
		<property name="connectionProperties">
		    <props>
		        <prop key="serverTimezone">Asia/Seoul</prop>
		        <prop key="allowMultiQueries">true</prop>
		    </props>
		</property>
	</bean>
	<bean id="sqlSessionFactory" class="com.test.framework.dao.RefreshableSqlSessionFactoryBean">
	   <property name="dataSource" ref="dataSource" />
	   <property name="mapperLocations" value="classpath*:/test/mapper/**/*-mapper.xml" />
	   <property name="configLocation" value="classpath:/test/mapper/mybatis-config.xml" />
	   <property name="interval" value="5000" />
	</bean>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.test.test1.**.dao" />
		<property name="annotationClass" value="com.test.framework.dao.Mapper" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>
	<!-- Transaction Manager -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean> 
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
  		<tx:attributes>
  		<tx:method name="get*" read-only="true"/>
  		<tx:method name="select*" read-only="true"/>
   		<tx:method name="*" rollback-for="Exception"/>
  		</tx:attributes>
 	</tx:advice>
 	<aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.test..dao.*DAO.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
    <tx:annotation-driven transaction-manager="transactionManager"/>
 </bean>

 

각 Bean에 대해 설명하자면, 

 

1) dataSource

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://2.2.2.2:3306/BASE_DB?useSSL=false"/>
    <property name="username" value="test"/>
    <property name="password" value="test123"/>
    <property name="connectionProperties">
        <props>
            <prop key="serverTimezone">Asia/Seoul</prop>
            <prop key="allowMultiQueries">true</prop>
        </props>
    </property>
</bean>
  • DriverManagerDataSource는 Spring에서 제공하는 데이터 소스 구현체로, JDBC를 통해 데이터베이스에 연결하기 위한 설정을 포함한다
  • driverClassName: JDBC 드라이버 클래스의 이름을 지정 ( Mysql 드라이버 사용)
  • url: 데이터베이스의 URL을 지정합니다. 여기서는 MySQL 데이터베이스에 연결한다
  • username: 데이터베이스에 접근하기 위한 사용자 이름
  • password: 데이터베이스에 접근하기 위한 비밀번호
  • connectionProperties: 추가적인 연결 속성을 설정합니다. 예를 들어, 서버의 시간대와 여러 쿼리를 허용하는 설정이 포함되어 있다

 

2) sqlSessionFactory 

<bean id="sqlSessionFactory" class="com.netcruz.framework.dao.RefreshableSqlSessionFactoryBean">
   <property name="dataSource" ref="dataSource" />
   <property name="mapperLocations" value="classpath*:/test/mapper/**/*-mapper.xml" />
   <property name="configLocation" value="classpath:/test/mapper/mybatis-config.xml" />
   <property name="interval" value="5000" />
</bean>
  • RefreshableSqlSessionFactoryBean은 MyBatis의 SqlSessionFactory를 생성하는 bean이다 ( MyBatis는 SQL 매핑을 지원하는 프레임워크 )
  • dataSource: 위에서 정의한 dataSource bean을 참조하여 데이터베이스 연결을 설정한다
  • mapperLocations: SQL 매핑 파일의 위치를 지정합니다. 여기서 지정된 경로에 있는 모든 매퍼 XML 파일을 로드한다
  • configLocation: MyBatis 설정 파일의 경로를 지정한다
  • interval: 매퍼 파일의 변경을 감지하여 자동으로 새로고침하는 주기를 설정(밀리초 단위)

3) MapperScannerConfigurer 

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.test.test1.**.dao" />
    <property name="annotationClass" value="com.test.framework.dao.Mapper" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
  • MapperScannerConfigurer는 MyBatis의 매퍼 인터페이스를 자동으로 스캔하고 Spring의 빈으로 등록하는 설정이다
  • basePackage: 매퍼 인터페이스가 위치한 패키지를 지정합니다. 이 패키지 내의 모든 매퍼 인터페이스가 스캔된다
  • annotationClass: 매퍼 인터페이스에 사용할 어노테이션을 지정, 이 어노테이션이 있는 인터페이스가 매퍼로 인식된다
  • sqlSessionFactoryBeanName: 사용할 SqlSessionFactory bean의 이름을 지정한다

 

4) transactionManager 

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
  • DataSourceTransactionManager는 Spring에서 JDBC를 사용할 때 데이터베이스 트랜잭션을 관리하는 데 사용된다
  • dataSource: 위에서 정의한 dataSource bean을 참조하여 트랜잭션을 관리할 데이터 소스를 지정한다

 

5) txAdvice 

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="get*" read-only="true"/>
        <tx:method name="select*" read-only="true"/>
        <tx:method name="*" rollback-for="Exception"/>
    </tx:attributes>
</tx:advice>
  • tx:advice는 AOP(Aspect Oriented Programming)를 사용하여 트랜잭션을 관리하는 조언(advice)이다
  • transaction-manager: 사용할 트랜잭션 매니저를 지정한다
  • tx:attributes: 특정 메서드에 대한 트랜잭션 속성을 정의한다
    • get* 및 select*로 시작하는 메서드는 읽기 전용 트랜잭션으로 설정된다
    • 모든 메서드는 예외가 발생할 경우 롤백하도록 설정된다

6) AOP Configuration

<aop:config>
    <aop:pointcut id="txPointcut" expression="execution(* com.test..dao.*DAO.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
  • AOP 설정 부분으로, 트랜잭션 조언을 적용할 지점을 정의한다
  • pointcut: 특정 패턴에 맞는 메서드 실행을 정의합니다. 여기서는 com.test..dao 패키지 내의 모든 DAO 클래스의 모든 메서드에 대해 트랜잭션 조언을 적용한다
  • advisor: 조언과 포인트컷을 연결하여, 지정된 포인트컷에 해당하는 메서드에 트랜잭션 조언을 적용한다

7) tx:annotation-driven

<tx:annotation-driven transaction-manager="transactionManager"/>
  • 어노테이션 기반의 트랜잭션 관리를 활성화한다, 이 설정을 통해 @Transactional 어노테이션을 사용하여 메서드 수준에서 트랜잭션을 관리할 수 있다
  • transaction-manager: 사용할 트랜잭션 매니저를 지정한다
728x90