Spring

MapSqlParameterSource 클래스는 왜 쓰는 걸까?

지안22 2023. 7. 16. 23:38

Repository(DAO)에서 데이터 베이스에 접근하는 쿼리를 작성 할 때,

기존까지는 JdbcTemplate 클래스를 사용해서 작성했는데, 이번에 처음 NamedParameterJdbcTemplate 클래스를 사용해 작성해보게 되었다.

 

JdbcTemplate 클래스로 User 테이블 접근 예시

    public List<User> findUserById(String userId) {
        String sql = "SELECT id, name "
                + "FROM user "
                + "WHERE id = ?";
                
        return jdbcTemplate.query(sql, userRowMapper(), userId);
    }

 

"?" 의 위치에 userId 변수를 대입한다.

 

NamedParameterJdbcTemplate 클래스로 User 테이블 접근 예시

    public List<User> findUserById(String userId) {
        String sql = "SELECT id, name "
                + "FROM user "
                + "WHERE id = :userId";

        SqlParameterSource param = new MapSqlParameterSource("userId", userId);

        return namedParameterJdbcTemplate.query(sql, param, userRowMapper());
    }

":userId" 변수를 바로 넣어 가독성을 좋게 만든다.

 

 

그러면서 MapSqlParameterSource 라는 클래스도 알게 되었는데, 이 클래스가 HashMap 클래스 Map.of() 를 사용하는 것과 뭐가 다른지 궁금해서 찾아보게 되었다.

 

결론부터 말하면

1. MapSqlParameterSource이 Builder 패턴처럼 사용할 수 있어, HashMap나 Map.of() 보다 가독성이 좋기 때문에 사용하는 것 같았다.

2. Hibernate/JPA와 동일한 접근 방식을 제공하기 때문에 사용하는 것 같았다.

 

MapSqlParameterSource 클래스 사용 예시 - 게시글 수정

    public void update(Article Article) {
        String sql = "UPDATE article " +
                "SET title = :title, contents = :contents " +
                "WHERE id = :articleId";

        SqlParameterSource param = new MapSqlParameterSource()
                .addValue("title", article.getTitle())
                .addValue("contents", article.getContents())
                .addValue("articleId", article.getId());

        namedParameterJdbcTemplate.update(sql, param);
    }

 

HashMap 사용 예시 - 게시글 수정

    public void update(Article Article) {
        String sql = "UPDATE article " +
                "SET title = :title, contents = :contents " +
                "WHERE id = :articleId";

        Map<String, Object> param = new HashMap<>();
        param.put("title", article.getTitle());
        param.put("contents", article.getContents());
        param.put("articleId", article.getId());

        namedParameterJdbcTemplate.update(sql, param);
    }

 

Map.of() 사용 예시 - 게시글 수정

    public void update(Article Article) {
        String sql = "UPDATE article " +
                "SET title = :title, contents = :contents " +
                "WHERE id = :articleId";

        Map<String, Object> param = Map.of("title", article.getTitle(),
                        "contents", article.getContents(),
                        "articleId", article.getId());


        namedParameterJdbcTemplate.update(sql, param);
    }

- Java9 부터 사용 가능

- 10개 까지 개수 제한

 

 

 

학습하고 스스로의 생각을 정리한 블로그이니, 부족한 점이 있다면 알려주시면 감사하겠습니다🙇🏻‍♀️

 

참고 자료

Spring 공식 문서 - NamedParameterJdbcTemplate

 

NamedParameterJdbcTemplate (Spring Framework 6.0.11 API)

Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a Java object via a RowMapper, and turning it into an iterable and closeable Stream. Query given SQL to create a prepared statement fr

docs.spring.io

Spring 공식 문서 - MapSqlParameterSource

 

MapSqlParameterSource

 

docs.spring.io

MapSqlParameterSource와 Collections.singletonMap() 비교

 

mapsqlparametersource vs java.util.map

I read in spring documentation that MapSqlParameterSource is just a wrapper over Map. What is the advantage of using MapSqlParameterSource instead of Map? public int countOfActorsByFirstName(String

stackoverflow.com

 

왜 MapSqlParameterSource를 쓰는걸까?

https://stackoverflow.com/questions/24742116/why-we-use-mapsqlparametersource

 

HashMap, Map.of()을 사용한 초기화

 

Map.of() 를 통한 Map 초기화 주의할 점

Java 9부터 사용할 수 있는 Map.of()를 통해 맵 데이터를 초기화하다가 주의할 점이 몇 가지 있어서 포스팅을 남기려 합니다.기존에는 맵을 초기화할 때 아래와 같이 진행했었습니다.하지만 Java 9 이

velog.io