Spring

[Spring] Spring JDBC(4): SimpleJdbcInsert로 DB에 데이터를 추가해보자!

깃짱 2023. 4. 22. 10:00
반응형
 

💋 SimpleJdbcInsert이란?

 

  • 스프링 프레임워크에서 제공하는 JDBC 확장 클래스 중 하나
  • JDBC로 SQL 쿼리를 실행하는 것보다 더 쉽고 간편하게 DB에 데이터를 '추가'하도록 도와준다.

 

💋 SimpleJdbcInsert를 사용해보자!

 

객체를 생성하고, 기능을 사용해서 DB에 데이터를 추가해보자!

 

 

✔ SimpleJdbcInsert 객체 생성해보자!

 

 

  1. 기본 생성자를 사용

 

SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource);

 

  1. JdbcTemplate 객체를 생성할 때 함께 생성

 

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate);

 

  1. SimpleJdbcInsertBuilder 클래스를 사용하여 생성

 

SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource)
        .withTableName("my_table")
        .usingColumns("column1", "column2", "column3")
        .usingGeneratedKeyColumns("id");

 

SimpleJdbcInsertBuilder 클래스는 SimpleJdbcInsert 객체를 생성하기 위한 빌더 클래스이다.
빌더 클래스의 각 메서드에 대해서 알아보자!

 

  • withTableName(): 추가할 테이블의 이름을 설정
  • usingColumns(): 추가할 열의 이름을 설정
  • usingGeneratedKeyColumns(): 자동 생성되는 열의 이름을 설정, AUTO_INCREMENT되는 열의 이름을 작성하면 됨!
    이 메서드를 사용하지 않으면 자동 증가 컬럼의 값을 받아올 수 없다.

 

세 번째 방법은 빌더 패턴을 사용하여 객체를 생성하기 때문에, 위 예시 코드에서 처럼 체인 메서드 호출 방식으로 여러 메서드를 연속해서 호출할 수 있다.

 

이렇게 성공적으로 객체를 생성했다. 그 다음은?

 

 

✔ SimpleJdbcInsert 객체를 사용해 DB에 데이터를 추가해보자!

 

  1. Map을 만들어서 데이터 추가하기: execute(Map<String, Object> parameters)

 

Map<String, Object> parameters = new HashMap<>();
parameters.put("column1", "value1");
parameters.put("column2", "value2");
parameters.put("column3", "value3");
Number id = simpleJdbcInsert.executeAndReturnKey(parameters);

 

parameters 맵 객체에 열의 이름과 그 열에 넣을 값을 설정한 후, executeAndReturnKey() 메서드를 호출한다.

 

  • execute(): DB에 데이터를 추가
  • executeAndReturnKey(): DB에 데이터를 추가 + 자동 생성된 key의 값을 반환 (AUTO_INCREMENT 열을 가져올 수 있음)

 

    /**
     * Map + insertActor.executeAndReturnKey id를 포함한 Customer 객체를 반환하세요
     */
    public Customer insertWithMap(Customer customer) {
        final String firstName = customer.getFirstName();
        final String lastName = customer.getLastName();
        final Map<String, String> parameters = Map.of(
                "first_name", firstName,
                "last_name", lastName);
        final int id = simpleJdbcInsert.executeAndReturnKey(parameters).intValue();
        return new Customer(id, firstName, lastName);
    }

 

  1. execute(SqlParameterSource parameterSource)

 

MyData myData = new MyData();
myData.setColumn1("value1");
myData.setColumn2("value2");
myData.setColumn3("value3");
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(myData);
Number id = simpleJdbcInsert.executeAndReturnKey(parameterSource);

 

MyData 클래스를 생성한 후에 setter를 통해서 각 객체의 값을 설정한다.


이후에 BeanPropertySqlParameterSource 클래스를 사용하여 SqlParameterSource 객체를 생성한다.

이 글BeanPropertySqlParameterSource에 대한 내용을 보면 이해가 쉬울 것 같다!

 

ParameterSourceexecuteAndReturnKey() 메서드의 파라미터로 함께 보내면, DB에 각 열에 맞게 저장이 되고, 자동 생성된 키 값을 받아올 수 있다.

 

예시 코드를 통해서 알아보자!

 

    public Customer insertWithBeanPropertySqlParameterSource(Customer customer) {
        final BeanPropertySqlParameterSource parameters = new BeanPropertySqlParameterSource(customer);
        final int id = simpleJdbcInsert.executeAndReturnKey(parameters).intValue();
        return new Customer(id, customer.getFirstName(), customer.getLastName());
    }

 

흠.. SimpleJdbcInsert를 만들려면 DataSource가 필요해 보인다.

 

DataSource는 뭘까...? 그건 다음 포스팅에서 공부할 예정!

반응형