JDBC RowMapper의 Result Set 을 잘 알지 못한자의 최후

김태훈·2023년 8월 1일
0
public Optional<NonSocialMember> findByEmailToVerifyInSecurity(String email) {
	String sql ="SELECT A.ID,U.ID,A.PASSWORD,U.EMAIL FROM MEMBER.USER AS U JOIN MEMBER.AUTH AS A ON U.ID = A.USER_ID WHERE U.EMAIL = ?";
    try{
    	NonSocialMember nonSocialMember = jdbcTemplate.queryForObject(sql,memberAuthRowMapper(),email);
        return Optional.of(nonSocialMember);
    }catch (EmptyResultDataAccessException e){
    	return Optional.empty();
    }
}


private RowMapper<NonSocialMember> memberAuthRowMapper(){
	return new RowMapper<NonSocialMember>() {
    	@Override
        public NonSocialMember mapRow(ResultSet rs, int rowNum) throws SQLException {
        	NonSocialMember member = NonSocialMember.builder()
            	.userId(rs.getLong("id"))
                .authId(rs.getLong("id"))
                .userPw(rs.getString("password"))
                .userEmail(rs.getString("email"))
                .build();
            return member;
        }
    };
}

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/RowMapper.html
[RowMapper 공식문서]

An interface used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object but don't need to worry about exception handling. SQLExceptions will be caught and handled by the calling JdbcTemplate.

앞에서 발생할 수 있는 문제가 무엇인지 아는가..
바로 ID라는 필드이름이 겹쳐서, USER테이블의 ID와 AUTH테이블의 ID가 겹쳐서 중복되서 받아온다는 사실이 문제이다.
그래서 Select Column을 할때, alias를 설정하여, 명확히 구분하고, RowMapper에서 해당 alias로 매핑할 수 있게 해주자.

public Optional<NonSocialMember> findByEmailToVerifyInSecurity(String email) {
	String sql ="SELECT A.ID AS A_ID ,U.ID AS U_ID,A.PASSWORD,U.EMAIL FROM MEMBER.USER AS U JOIN MEMBER.AUTH AS A ON U.ID = A.USER_ID WHERE U.EMAIL = ?";
    try{
    	NonSocialMember nonSocialMember = jdbcTemplate.queryForObject(sql,memberAuthRowMapper(),email);
        return Optional.of(nonSocialMember);
    }catch (EmptyResultDataAccessException e){
    	return Optional.empty();
    }
}


private RowMapper<NonSocialMember> memberAuthRowMapper(){
	return new RowMapper<NonSocialMember>() {
    	@Override
        public NonSocialMember mapRow(ResultSet rs, int rowNum) throws SQLException {
        	NonSocialMember member = NonSocialMember.builder()
            	.userId(rs.getLong("u_id"))
                .authId(rs.getLong("a_id"))
                .userPw(rs.getString("password"))
                .userEmail(rs.getString("email"))
                .build();
            return member;
        }
    };
}
profile
기록하고, 공유합시다

0개의 댓글