Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

In a previous blog, I showed how to use JPA to read and write to a database with JPA. Spring Batch – reading and writing JPA. We prefer to use Spring Data Repositories instead of using the JPA directly. Thankfully, there is a way to use a Spring Data Repository directly with Spring Batch.

RepositoryItemWriter

This is how a RepositoryItemWriter is declared. It follows the normal ItemWriter pattern. It needs a Spring Data Repository and to know what method should be called on the repository, save in this case.

@Bean
public RepositoryItemWriter<WagerActivity> writer() {
    RepositoryItemWriter<WagerActivity> writer = new RepositoryItemWriter<>();
    writer.setRepository(wagerActivityRepository);
    writer.setMethodName("save");
    return writer;
}

Spring Batch 4 has the concept of Builders. This is an example of what the Builder for this repository should look like:

return new RepositoryItemWriterBuilder<WagerActivity>()
                .methodName("save").repository(wagerActivityRepository).build();

Repository Declaration

A repository is an interface that surrounds an Entity. My interface is as follows:

public interface WagerActivityRepository extends JpaRepository<WagerActivity, Integer> {
}

Save Method

I don’t like hard-coded Strings, so I figured out how to get the save method name from Spring Data. The first thing I had to do was get the RepositoryMetadata. I created a DefaultRepositoryMetadata with my repository to instantiate the object. I then instantiated a DefaultCrudMethods with the repository metadata. Once I had that, I could get the save method and the name that should be used to access it. I removed the need for a hard-coded String, but I don’t think it is worth the effort. Too bad there isn’t a Enum.

@Bean
public RepositoryMetadata repositoryMetadata() {
    return new DefaultRepositoryMetadata(WagerActivityRepository.class);
}
@Bean
public RepositoryItemWriter<WagerActivity> writer() {
    DefaultCrudMethods defaultCrudMethods = new DefaultCrudMethods(repositoryMetadata());
    RepositoryItemWriter<WagerActivity> writer = new RepositoryItemWriter<>();
    writer.setRepository(wagerActivityRepository);
    writer.setMethodName(defaultCrudMethods.getSaveMethod().getName());
    return writer;
}

December 7th, 2017

Posted In: java ninja, Javaninja, Spring Batch, Spring Data JPA

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com