728x90
Mybaits란?
데이터 베이스를 쉽게 다룰 수 있도록 도와주는 오픈소스 ORM(Object-Relational Mapping)입니다.
데이터베이스 쿼리와 프로그래밍 언어 코드를 분리할 수 있습니다.
동적 쿼리 작성이 가능합니다.
// xml 파일
<select id="getUserList" resultType="User">
SELECT * FROM users
<where>
<if test="name != null"> // 동적 쿼리
AND name = #{name}
</if>
<if test="email != null"> // 동적 쿼리
AND email = #{email}
</if>
</where>
</select>
출처: https://ccomccomhan.tistory.com/130 [[꼼꼼한 개발자] 꼼코더:티스토리]
Mybatis 사용순서
1. 필요한 의존성 추가
- mybatis
- mybatis-spring
2. mybatis 설정하기
Mybatis 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">
<configuration>
<!-- db.properties 외부 파일로부터 DB연결을 위한 프로퍼티를 가져옵니다-->
<properties resource="oracle.properties" />
<!-- TypeAliases 타입 별칭은 자바 타입에 대한 좀더 짧은 이름이다. 오직 XML 설정에서만 사용되며, 타이핑을 줄이기 위해 존재한다-->
<typeAliases>
<typeAlias alias="userVO" type="com.lec08.dao.BoardVO" />
</typeAliases>
<!-- DBCP MyBatis 는 여러개의 환경으로 설정될 수 있다. 다중 환경을 설정할 수는 있지만, SqlSessionFactory 인스턴스마다 한개만 사용할 수 있다는
것이다.-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" /> <!-- MANAGED -->
<dataSource type="POOLED">
<property name="driver" value="${lec.driver}" />
<property name="url" value="${lec.url}" />
<property name="username" value="${lec.username}" />
<property name="password" value="${lec.userpw}" />
</dataSource>
</environment>
</environments>
<!-- mapper SQL문이 맵핑되어 있다.-->
<mappers>
<mapper resource="board-map-lec08.xml" />
</mappers>
</configuration>
3. Mapper XML 작성
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="boardNameSpace">
<resultMap id="boardResultMap" type="com.lec08.dao.BoardVO">
<id property="seq" column="seq" />
<result property="title" column="title" />
<result property="contents" column="contents" />
<result property="regid" column="regid" />
<result property="regdate" column="regdate" />
<collection property="replies" ofType="com.lec08.dao.ReplyVO" select="getReplyBySeq" column="seq" />
</resultMap>
<resultMap id="replyResultMap" type="com.lec08.dao.ReplyVO">
<id property="rseq" column="rseq" />
<result property="reply" column="reply" />
<result property="regid" column="r_regid" />
<result property="regdate" column="r_regdate" />
<result property="seq" column="bseq" />
</resultMap>
<!-- Board 리스트 -->
<select id="getBoardBySeq" parameterType="com.lec08.dao.BoardVO" resultMap="boardResultMap">
SELECT seq, title, contents, regid, regdate
FROM board1
WHERE seq = #{seq}
</select>
<!-- 관련된 Reply 리스트 -->
<select id="getReplyBySeq" resultMap="replyResultMap">
SELECT rseq, reply, r_regid, r_regdate, bseq
FROM reply
WHERE bseq = #{seq}
</select>
<resultMap id="boardReplyResultMap" type="com.lec08.dao.BoardVO">
<id property="seq" column="seq" />
<result property="title" column="title" />
<result property="contents" column="contents" />
<result property="regid" column="regid" />
<result property="regdate" column="regdate" />
<collection property="replies" ofType="com.lec08.dao.ReplyVO">
<id property="rseq" column="rseq" />
<result property="reply" column="reply" />
<result property="regid" column="r_regid" />
<result property="regdate" column="r_regdate" />
<result property="seq" column="bseq" />
</collection>
</resultMap>
<!-- Board + Reply 조인 -->
<select id="getBoardReplyBySeq" parameterType="com.lec08.dao.BoardVO" resultMap="boardReplyResultMap">
SELECT b.*,r.*
FROM board1 b, reply r
WHERE b.seq = r.bseq AND b.seq = #{seq}
</select>
<insert id="insertUser" parameterType="com.lec08.dao.UserVO">
<selectKey keyProperty="userSeq" resultType="int" order="BEFORE">
SELECT user_seq.nextval as a FROM dual
</selectKey>
insert into user3
values
(#{userSeq},#{userId},#{userName},#{userPw},#{userGubun})
</insert>
<resultMap id="UserAllResultMap" type="com.lec08.dao.UserVO">
<result property="userSeq" column="user_seq" />
<result property="userId" column="user_id" />
<result property="userName" column="user_name" />
<result property="userPw" column="user_pw" />
<result property="userGubun" column="user_gubun" />
</resultMap>
<select id="getUserAll" resultMap="UserAllResultMap">
SELECT * FROM user3
</select>
<resultMap id="UserAllResultMap1" type="com.lec08.dao.UserVO">
<result property="userSeq" column="user_seq" />
<result property="userId" column="user_id" />
<result property="userName" column="user_name" />
<result property="userPw" column="user_pw" />
<result property="userGubun" column="user_gubun" />
</resultMap>
<select id="getloginCheck" parameterType="com.lec08.dao.UserVO" resultMap="UserAllResultMap1">
SELECT * FROM user3 WHERE user_id=#{userId} AND user_pw=#{userPw}
</select>
<update id="updateUser" parameterType="com.lec08.dao.UserVO">
UPDATE user3 SET user_pw = #{userPw} WHERE user_id = #{userId}
</update>
<delete id="userDelete" parameterType="int">
delete from user3 where user_seq = #{userSeq}
</delete>
</mapper>
4. Mapper 사용
@Service
public class UserService {
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
// 유저 조회
public User getUserById(int id) {
return userMapper.getUserById(id);
}
// 유저 등록
public void insertUser(User user) {
userMapper.insertUser(user);
}
// ... 다른 메서드들
}
출처: https://ccomccomhan.tistory.com/130 [[꼼꼼한 개발자] 꼼코더:티스토리]
'KOSTA : 클라우드 네이티브 애플리케이션 개발 전문가 양성과정' 카테고리의 다른 글
06/28 53일차 Spring/ Mybatis-Spring/ 트랜잭션 annotation/ 트랜잭션 XML/ 트랜잭션 AOP/ 데이터소스와 트랜잭션매니저 (0) | 2024.06.28 |
---|---|
06/27 52일차 Spring/ Mybatis-Spring (0) | 2024.06.27 |
06/21 48일차 Spring/ JNDI / Property 파일설정 (0) | 2024.06.21 |
06/17 44일차 Spring REST/ AJAX (0) | 2024.06.18 |
06/14 43일차 Spring (0) | 2024.06.14 |