Java Reference
In-Depth Information
aren't as prevalent in other processing in today's enterprise. Instead, the relational database has taken
over. As such, the batch process must be able to not only read from a database (as you saw in Chapter 7)
but write to it as well. The next section looks at the more common ways to handle writing to a database
using Spring Batch.
Database-Based ItemWriters
Writing to a database offers a different set of constraints than file-based output. First, databases are
transactional resources, unlike files. Because of this, you can include the physical write as part of the
transaction instead of segmenting it as file-based processing does. Also, there are many different options
for how to access a database. JDBC, Java Persistence API (JPA), and Hibernate all offer unique yet
compelling models for handling writing to a database. This section looks at how to use JDBC, Hibernate,
and JPA to write the output of a batch process to a database.
JdbcBatchItemWriter
The first way you can write to the database is the way most people learn how to access a database with
Spring in general, via JDBC. Spring Batch's JdbcBatchItemWriter uses the JdbcTemplate and its batch SQL
execution capabilities to execute all of the SQL for a single chunk at once. This section looks at how to
use JdbcBatchItemWriter to write a step's output to a database.
org.springframework.batch.item.database.JdbcBatchItemWriter isn't much more than a thin
wrapper around Spring's org.springframework.jdbc.support.JdbcTemplate , using the
JdbcTemplate.batchUpdate or JdbcTemplate.execute method depending on if named parameters are
used in the SQL to execute mass database insert/updates. The important thing to note about this is that
Spring uses PreparedStatement 's batch-update capabilities to execute all the SQL statements for a single
chunk at once instead of using multiple calls. This greatly improves performance while still allowing all
the executions to execute within the current transaction.
To see how the JdbcBatchItemWriter works, again you work with the same input you used with the
file-based writers, but you use it to populate a customer database table instead of writing a file. Figure 9-
3 shows the design of the table into which you're inserting the customer information.
Figure 9-3. Customer table design
As you can see in Figure 9-3, the columns of the Customer table match up virtually one-to-one with
the elements in the customer.csv file. The only difference is the id field, which you let the database
populate for you. In order to insert the values into the table, you need to build the SQL in either of two
 
Search WWH ::




Custom Search