This post is part of a series delving into the details of the JSR-352 (Java Batch) specification. Each post examines a very specific part of the specification and looks at how it works and how you might use it in a real batch application.To start at the beginning, follow the link to the first post.
The next post in the series is here
.This series is also available as a podcast on iTunes, Google Play, Stitcher, or use the link to the RSS feed.
By now this should be pretty obvious. The JdbcWriter extends the JdbcConnectionConfiguration which gets all the injected attributes to establish a connection to your database. Just like the other JDBC batch artifacts.
And you’re going to want to specify some SQL statement to do the insert of each row into whatever table it goes into. And just like JdbcReader you get to specify one. No surprises here either.
The only thing left to do is figure out how to convert the Object that your ItemProcessor provided into something that can be inserted into your database table.
The FlatFileWriter had a method you could extend to handle the conversion. For the JdbcReader we had a RecordMapper that mapped the record that was read into an Object. But in this case we want to go the other way. We’ve got an Object to start with, which is probably why the interface you implement here is called ObjectMapper.
The ObjectMapper gets passed the Object provided by the ItemProcessor and the PreparedStatement that resulted in calling prepareStatement on the database connection with your specified SQL. In your ObjectMapper you get to figure out how to extract data from your processing result and push it into the PreparedStatement so that it can be executed.
One neat little bit to this is that the JdbcWriter calls the ObjectMapper for every Object it was passed (all the results for this chunk of processing) and then it calls executeBatch on the resulting complete PreparedStatement. This will essentially insert all the rows needed, all at once. Generally, this gives you much better performance that doing the inserts one by one.
We’ve got a bit of a theme going here. All of these different implementations of batch artifacts handle the basics of dealing with whatever datasource is involved while leaving relatively easy ways for you to get in there and fiddle with things where your actual data has to come into play.