spring Mybatis

이경현·2024년 11월 4일

스프링 설정하고 마이바티스 연동하기 순서정리 >>

  1. 레거시 프로젝트 생성
    pom.xml 파일에 Dependency추가(필요한 라이브러리 추가해주기)

  2. 2-1. src/resources 에 config 패키지 생성
    그 안에 mybatis_config.xml 파일 생성

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!-- mybatis 설정파일  -->
    <configuration> 
    <typeAliases>
    	<typeAlias alias="mv" type="com.myaws.myapp.domain.MemberVo"/>

// 입력해주기





2-2. src/resources 에 mappers 패키지 생성해서 
그 안에 memberMapper.xml 파일 생성 : 여기에 쿼리문 작성할거임
이렇게 넣고 mapper 사이에 나중에 원하는 쿼리문 작성하기 ```
  1. DataSource 설정

3-1. root-context.xml 파일에 db 연결할 아이디 등 넣어주기
root-context.xml 에서 namespace 탭 들어가서 필요한 http 설정 체크해주기
aop, beans, context, jee, task, util등 체크되어있는지 확인하기

데이터베이스 접속에 필요한 정보들을 등록해주기
아래와 같이 작성 :

<beans>
<!-- 콩만들때  필요한 원재료  창고 주소랑  비밀번호 알려주기 -->
<bean id = "db" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>		
			<property name="url" value = "jdbc:mysql://127.0.0.1:3306/aws0822?useSSL=false&amp;serverTimeZone=UTC&amp;allowPublicKeyRetrieval = true"/>
			<property name = "username" value = "root"/>
			<property name = "password"	value = "1234"/>
		</bean>
		<!--  콩만드는 공장 생성 -->
		<bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 참조값은 위에 있는 db를 참조해서 mybatis와 mysql을 연결하겠다 -->
			<property name="dataSource" ref = "db"/>
			<property name="mapperLocations" value = "classpath:mappers/*.xml"/>
			<!--  mybatis 환경설정에 관련된정보는 여기에 담겠다-->		
			<property name="configLocation" value = "classpath:config/mybatis_config.xml"/>

		</bean>
		
		<!--  공장에서나온 제품을 사용하는 실질적인 장소 찍어줌 -->
		<bean id="sqlSession" class = "org.mybatis.spring.SqlSessionTemplate">
			<constructor-arg name = "sqlSessionFactory" ref = "sqlSessionFactory"/>
		</bean>	
			
		<context:component-scan base-package="com.myaws.myapp">
			<context:exclude-filter type = "annotation" expression = "org.springframework.stereotype.Controller"/>
		</context:component-scan>
		
</beans>

그다음 mapper를 만든다

src/main/java 아래에
com.myaws.myapp 패키지 안에
controller
domain
persistence
service
패키지 생성

persistence 안에 (영속성주기)
MemberMapper 인터페이스 생성해주기

  • 여기서는 mybatis에서 사용할 메서드들을 정의해둔다
  • 구현문은 없고 선언만 해준다
  • 쿼리문은 위에 있는 memberMapper 클래스에서 한다(src/main/resoueces/ 아래에 있는 mapper패키지 안에 memberMapper.xml 파일에서 쿼리문 작성후 호출)

0개의 댓글