본문 바로가기

Spring/Spring JDBC

[Spring] [Spring JDBC] 5. Spring JDBC 실습 진행 3 - insert(), update()

앞선 selectAll() 실습에서 ApplicationConfig 관련 설정은 전부 다 했으므로, RoleDao 클래스에 insert, update 관련 부분만 작성해주면 된다.

 

1. RoleDaoSqls 에 쿼리문 추가하기

update는 sql문을 추가해주어야 한다. 따라서, RoleDaoSqls에 다음과 같은 sql을 추가하자

public class RoleDaoSqls {
    public static final String SELECT_ALL = "SELECT role_id, description FROM role ORDER BY role_id";
    public static final String UPDATE = "UPDATE role SET description = :description where role_id = :roleId";
}

2. RoleDao에 SimpleJdbcInsert 추가하기

update()는, NamedParameterJdbcTemplate를 사용하는데 이미 필드로 가지고 있으므로, 설명 생략하겠다.

 

insert()는, Spring JDBC에서 insert를 도와주는 객체가 SimpleJdbcInsert이고 이미 구현되어 있으므로, 사용하면 된다.

아래와 같이 SimpleJdbcInsert 객체를 필드로 추가해준 후,

private SimpleJdbcInsert insertAction;

아래와 같이, RoleDao의 생성자에 다음과 같은 코드를 넣어서, RoleDao에 SimpleJdbcInsert를 생성자 주입하면 된다.

(withTableName : 어떤 테이블에 insert 할 지 명시해주기)

// spring이 datasource를 자동으로 주입해준다
public RoleDao(DataSource dataSource) {
    this.jdbc = new NamedParameterJdbcTemplate(dataSource);
    this.insertAction = new SimpleJdbcInsert(dataSource)
            .withTableName("role"); // 1. 어떤 테이블에 insert 할 지
}

 

3. RoleDao에 insert(),update() 메서드 추가하기

insert문은 따로 sql이 필요가 없으므로, 그냥 SimpleJdbcInsert객체의 execute() 메서드를 실행시키면 된다.

public int insert(Role role) {
    SqlParameterSource params = new BeanPropertySqlParameterSource(role); // 2. 맵 객체 리턴
    return insertAction.execute(params); // 3. execute()
}

 

update는 NamedParameterJdbcTemplate의 update()를 수행하면 된다

param은 update의 sql문의 파라미터에 바인딩 할 값을 가지고 있는 맵 객체라고 생각하면 된다.

 

update() 메서드를 실행할 때,

1. role 객체를 받아서

2. 해당 role 객체를 BeanPropertySqlParameterSource를 이용하여 sql문에 바인딩 할 수 있는 map 객체로 만든 후

3. update에 인자로 넣어준다

public int update(Role role) {
    SqlParameterSource params = new BeanPropertySqlParameterSource(role);
    return jdbc.update(UPDATE, params);

}

 

4. main에서 실제 insert(), update() 메서드 실행해보기

public class JdbcTest {
    public static void main(String[] args) {
        ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);

        RoleDao roleDao = ac.getBean(RoleDao.class);

        Role role = new Role();
        role.setRoleId(201);
        role.setDescription("PROGRAMMER");

        int cnt = roleDao.insert(role);
        System.out.println(cnt+"건 입력하셨습니다");

        int cnt = roleDao.update(role);
        System.out.println(cnt+"건 수정하였습니다");

    }
}