MyBatis
mybatis – 마이바티스 3 | 시작하기
mybatis.org
1. mybatis.jar 파일 설치
Releases · mybatis/mybatis-3 (github.com)
Releases · mybatis/mybatis-3
MyBatis SQL mapper framework for Java. Contribute to mybatis/mybatis-3 development by creating an account on GitHub.
github.com
프로젝트 우클릭 → [properties] → [Java Build Path] → class path에 추가
2. SqlSessionFactory 생성
Java 애플리케이션 초기화 부분이나 DB 작업 전에 실행
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
init() 안에 사용한 예시
public void init(){
try{
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
}
3. mybatis-config.xml 파일 생성
resource의 경로에 생성
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
driver, url, username, password 값 입력
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/b1?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
mapper는 뒤에서 다시 봄
4. SqlSessionFactory에서 SqlSession 만들기
try (SqlSession session = sqlSessionFactory.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
}
BlogMapper.class: 주어진 SQL 구문의 파라미터와 리턴값을 설명하는 인터페이스. 문자열 처리 오류나 타입 캐스팅 오류 없이 좀더 안전하고 깔끔하게 실행할 수 있게 함.
init() 안에 사용한 예시
public void init(){
try{
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession()
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
}
}
5. SQL문이 있는 xml 파일 작성
예) addrMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
<select id="selectBlog" resultType="Blog" ParameterType = "">
select * from Blog where id = #{id}
</select>
해당 sql을 메서드와 연결해서 처리
id: 메서드명
resultType: 리턴
parameterType: 매개변수
6. interface 생성
public interface AddrMapper{
public ArrayList<Addr> methodA();
}
인터페이스 상속과 메소드 내부 내용 작성은 MyBatis가 알아서 함
인터페이스에서 지정해줘야 할 정보: 리턴 타입, 메소드명, 매개변수
7. SQL문 xml파일의 namespace에 interface 파일 표기
xml 파일
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
<!-- mapper namespace 부분 -->
<mapper namespace="org.mybatis.example.BlogMapper">
<!-- 수정 -->
<mapper namespace="packageName.AddrMapper">
select 태그 메서드에 맞게 수정, SQL문 필요에 따라 수정
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
<!-- 수정 -->
<select id="methodA" resultType="addr.Addr">
select * FROM tb_address
</select>
리턴 타입은 ArrayList<Addr>이지만 패키지.클래스명으로 작성