22 Ağustos 2017 Salı

SpringBatch JdbcCursorItemReader Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcCursorItemReader;
constructor
Şöyle yaparız.
JdbcCursorItemReader<Foo> databaseReader = new JdbcCursorItemReader<>();
setDataSource metodu
Şöyle yaparız.
DataSource dataSource = ...;
databaseReader.setDataSource(dataSource);
setRowMapper metodu
Şu satırı dahil ederiz.
import org.springframework.jdbc.core.BeanPropertyRowMapper;
Şöyle yaparız.
databaseReader.setRowMapper(new BeanPropertyRowMapper<>(Foo.class));
setSql metodu
Örnek
Şöyle yaparız.
private static final String QUERY_FIND_STUDENTS =
        "SELECT " +
            "email_address, " +
            "name, " +
            "purchased_package " +
        "FROM STUDENTS " +
        "ORDER BY email_address ASC";

databaseReader.setSql(QUERY_FIND_STUDENTS);
Örnek
Şöyle yaparız.
@Autowired
public DataSource dataSource;


@Bean
public JdbcCursorItemReader<User> reader() {
  JdbcCursorItemReader<User> reader = new JdbcCursorItemReader<User>();
  reader.setDataSource(dataSource);
  reader.setSql("SELECT id,name FROM employee");
  reader.setRowMapper(new UserRowMapper());
  return reader;
}

public class UserRowMapper implements RowMapper<User> {

  @Override
  public User mapRow(ResultSet rs, int rowNum) throws SQLException {
    User user = new User();
    user.setId(rs.getInt("id"));
    user.setName(rs.getString("name"));

    return user;
  }

}

Hiç yorum yok:

Yorum Gönder