View Javadoc

1   package org.springframework.batch.sample.common;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   
6   import javax.sql.DataSource;
7   
8   import org.springframework.batch.core.partition.support.Partitioner;
9   import org.springframework.batch.item.ExecutionContext;
10  import org.springframework.jdbc.core.JdbcOperations;
11  import org.springframework.jdbc.core.JdbcTemplate;
12  
13  /**
14   * Simple minded partitioner for a range of values of a column in a database
15   * table. Works best if the values are uniformly distributed (e.g.
16   * auto-generated primary key values).
17   *
18   * @author Dave Syer
19   *
20   */
21  public class ColumnRangePartitioner implements Partitioner {
22  
23  	private JdbcOperations jdbcTemplate;
24  
25  	private String table;
26  
27  	private String column;
28  
29  	/**
30  	 * The name of the SQL table the data are in.
31  	 *
32  	 * @param table the name of the table
33  	 */
34  	public void setTable(String table) {
35  		this.table = table;
36  	}
37  
38  	/**
39  	 * The name of the column to partition.
40  	 *
41  	 * @param column the column name.
42  	 */
43  	public void setColumn(String column) {
44  		this.column = column;
45  	}
46  
47  	/**
48  	 * The data source for connecting to the database.
49  	 *
50  	 * @param dataSource a {@link DataSource}
51  	 */
52  	public void setDataSource(DataSource dataSource) {
53  		jdbcTemplate = new JdbcTemplate(dataSource);
54  	}
55  
56  	/**
57  	 * Partition a database table assuming that the data in the column specified
58  	 * are uniformly distributed. The execution context values will have keys
59  	 * <code>minValue</code> and <code>maxValue</code> specifying the range of
60  	 * values to consider in each partition.
61  	 *
62  	 * @see Partitioner#partition(int)
63  	 */
64  	public Map<String, ExecutionContext> partition(int gridSize) {
65  
66  		int min = jdbcTemplate.queryForInt("SELECT MIN(" + column + ") from " + table);
67  		int max = jdbcTemplate.queryForInt("SELECT MAX(" + column + ") from " + table);
68  		int targetSize = (max - min) / gridSize + 1;
69  
70  		Map<String, ExecutionContext> result = new HashMap<String, ExecutionContext>();
71  		int number = 0;
72  		int start = min;
73  		int end = start + targetSize - 1;
74  
75  		while (start <= max) {
76  
77  			ExecutionContext value = new ExecutionContext();
78  			result.put("partition" + number, value);
79  
80  			if (end >= max) {
81  				end = max;
82  			}
83  			value.putInt("minValue", start);
84  			value.putInt("maxValue", end);
85  			start += targetSize;
86  			end += targetSize;
87  			number++;
88  		}
89  
90  		return result;
91  
92  	}
93  
94  }