Add usePersist chain method to JpaItemWriterBuilder

This commit is contained in:
Ruslan Mustaev
2020-02-02 20:56:52 +03:00
committed by Mahmoud Ben Hassine
parent 06212e91aa
commit 88ffd06cce
2 changed files with 35 additions and 2 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,6 +30,7 @@ import org.springframework.util.Assert;
public class JpaItemWriterBuilder<T> {
private EntityManagerFactory entityManagerFactory;
private boolean usePersist = false;
/**
* The JPA {@link EntityManagerFactory} to obtain an entity manager from. Required.
@@ -44,6 +45,19 @@ public class JpaItemWriterBuilder<T> {
return this;
}
/**
* Set whether the entity manager should perform a persist instead of a merge.
*
* @param usePersist defaults to false
* @return this instance for method chaining
* @see JpaItemWriter#setUsePersist(boolean)
*/
public JpaItemWriterBuilder<T> usePersist(boolean usePersist) {
this.usePersist = usePersist;
return this;
}
/**
* Returns a fully built {@link JpaItemWriter}.
*
@@ -55,6 +69,7 @@ public class JpaItemWriterBuilder<T> {
JpaItemWriter<T> writer = new JpaItemWriter<>();
writer.setEntityManagerFactory(this.entityManagerFactory);
writer.setUsePersist(this.usePersist);
return writer;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,4 +84,22 @@ public class JpaItemWriterBuilderTests {
assertEquals("Incorrect message", "EntityManagerFactory must be provided", ise.getMessage());
}
}
@Test
public void testPersist() throws Exception {
JpaItemWriter<String> itemWriter = new JpaItemWriterBuilder<String>()
.entityManagerFactory(this.entityManagerFactory)
.usePersist(true)
.build();
itemWriter.afterPropertiesSet();
List<String> items = Arrays.asList("foo", "bar");
itemWriter.write(items);
verify(this.entityManager).persist(items.get(0));
verify(this.entityManager).persist(items.get(1));
}
}