MyBatis

스프링에서 DB를 다루기 위해서 사용하는 오픈 소스 프레임워크.

특징

My batis 설정 단계

1. mvn 레포지터리 에서 필요한 라이브러리 3개를 pom.xml 에 저장 (위치 주의!)

<aside> 💡 <spring> 구문이 끝난 뒤에!! 해당 구문을 넣어야 한다. spring 설치가 끝난 뒤에만 가능.

</aside>

<!-- 마이바티스 설정 -->
<!-- <https://mvnrepository.com/artifact/org.mybatis/mybatis> -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.8</version>
</dependency>
<!-- <https://mvnrepository.com/artifact/org.mybatis/mybatis-spring> -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>
<!-- <https://mvnrepository.com/artifact/org.springframework/spring-jdbc> -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<!-- 마이바티스 종료 -->

2. DAO기능의 xml 파일(idao.xml) 생성 (주소 입력)

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "<https://mybatis.org/dtd/mybatis-3-mapper.dtd>">

<mapper namespace="com.ezen.(주소입력).Service">

</mapper>

3. servlet-context.xml 파일에 기본설정 → mybatis 설치 (주소 입력)

	<!-- 마이 바티스 설치 시작 -->
    <beans:bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <beans:property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
        <beans:property name="username" value="ezen"/>
        <beans:property name="password" value="12345"/>
    </beans:bean>   
    <beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="mapperLocations" value="classpath:com/ezen/(주소입력)/*.xml"/>
    </beans:bean>   
    <beans:bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <beans:constructor-arg index="0" ref="sqlSessionFactory"></beans:constructor-arg>
    </beans:bean>
	<!-- 마이 바티스 설치 종료 -->

4. 홈컨트롤러에 sqlsession 객체 선언 자동 주입

@Controller
public class HomeController {
	   @Autowired //쿼리문이 실행될 때마다 드라이브 설정 환경을 자동으로 연결시켜줌
	   SqlSession sqlSession;
	…
}

5. Service 인터페이스 생성

6. 각 메소드에서 각 기능 구현.

getMapper 메소드는 MyBatis의 Mapper 인터페이스를 구현한 객체를 반환합니다. 이 메소드를 사용하여 Mapper 인터페이스를 가져오면, 해당 인터페이스의 메소드들은 MyBatis가 제공하는 SQL 매핑 구성에 따라 데이터베이스와 상호 작용할 수 있습니다.

일반적으로 MyBatis에서는 인터페이스와 XML 파일을 사용하여 SQL 쿼리를 정의합니다. 인터페이스에는 데이터베이스에 액세스하는 메소드가 선언되어 있고, XML 파일에는 메소드와 실제 SQL 쿼리가 매핑됩니다. getMapper 메소드를 사용하여 인터페이스를 가져오면, 해당 인터페이스의 메소드 호출은 MyBatis가 미리 정의한 SQL 쿼리를 실행하게 됩니다.

즉, 당신이 말씀하신 대로, **getMapper**를 통해 가져온 인터페이스의 메소드명과 XML 파일의 id를 연결하여 MyBatis의 매핑 구성을 통해 데이터베이스에 접근하고 쿼리를 실행할 수 있습니다. 이것은 개발자가 Java 인터페이스를 통해 SQL을 쉽게 작성하고 관리할 수 있도록 해줍니다.


예제

이름, 나이, 주소를 입력하고 DB에 저장, 출력하는 코드

사전 준비 : web.xml에서 한글 코드 깨짐 방지 해주기!

Untitled

Untitled

Untitled

Untitled

MyBatis 설정 파일 모음