mybatis vo 매핑

MyBatis는 자바 객체와 SQL 쿼리의 매핑을 간단하게 수행할 수 있는 ORM(Object-Relational Mapping) 프레임워크입니다. 이를 통해 개발자는 데이터베이스와의 상호작용을 보다 편리하게 처리할 수 있습니다. 이번 글에서는 MyBatis에서 VO(Value Object)를 매핑하는 방법에 대해 알아보겠습니다.

VO 클래스 작성하기

VO 클래스는 데이터베이스의 특정 테이블과 매칭됩니다. 일반적으로 테이블의 각 컬럼은 VO 클래스의 멤버 변수로 정의됩니다. 컬럼과 멤버 변수의 이름이 동일하거나, 어노테이션을 사용하여 매핑 관계를 명시할 수 있습니다.

public class UserVO {
    private int id;
    private String username;
    private String email;
    
    // Getter and Setter methods
}

위의 예제에서 UserVO 클래스는 데이터베이스의 “users” 테이블과 매칭됩니다. 각 컬럼은 id, username, email이라는 멤버 변수와 매칭됩니다.

MyBatis 매핑 XML 작성하기

MyBatis에서는 VO 클래스와 SQL 쿼리를 매핑하는 XML 파일을 작성해야 합니다. 이를 통해 어떤 SQL 쿼리를 실행할지, 어떤 매개변수를 전달해야 하는지를 정의할 수 있습니다.

<mapper namespace="com.example.UserMapper">
    <resultMap id="UserResultMap" type="UserVO">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="email" column="email"/>
    </resultMap>
    
    <select id="getUserById" resultMap="UserResultMap">
        SELECT * FROM users WHERE id = #{id}
    </select>
    
    <!-- 다른 SQL 쿼리들 -->
</mapper>

위의 예제에서는 “com.example.UserMapper” 네임스페이스를 가진 매퍼 파일에 UserVO 클래스와 SQL 쿼리를 매핑하고 있습니다.

MyBatis 설정 파일 작성하기

매퍼 파일을 사용하기 위해 MyBatis 설정 파일에 매퍼 파일을 등록해야 합니다. 아래는 MyBatis 설정 파일의 예시입니다.

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydatabase"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="com/example/UserMapper.xml"/>
        <!-- 다른 매퍼 파일들 -->
    </mappers>
</configuration>

위의 예시에서는 MySQL 데이터베이스를 사용하고 있으며, 데이터베이스 접속 정보와 매퍼 파일의 경로를 설정 파일에 작성하고 있습니다.

VO 매핑 사용하기

매퍼 파일의 설정이 완료되면, VO 매핑을 사용하여 데이터베이스와 상호작용할 수 있습니다.

public interface UserMapper {
    UserVO getUserById(int id);
}

위의 예시에서는 UserMapper 인터페이스를 정의하고, getUserById 메서드를 선언하고 있습니다. 이 메서드는 id 매개변수에 해당하는 사용자 정보를 반환합니다.

이제 이 인터페이스를 사용하여 MyBatis에서 VO 매핑을 수행할 수 있습니다.

SqlSession sqlSession = sqlSessionFactroy.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserVO userVO = userMapper.getUserById(1);

위의 예시에서는 SqlSession을 통해 UserMapper 인터페이스를 가져오고, getUserById 메서드를 호출하여 VO 매핑을 수행하고 있습니다.

#MyBatis #ORM