-
-
Notifications
You must be signed in to change notification settings - Fork 550
Expand file tree
/
Copy pathJPAPersonRepository.java
More file actions
51 lines (40 loc) · 1.47 KB
/
Copy pathJPAPersonRepository.java
File metadata and controls
51 lines (40 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package models;
import play.db.jpa.JPAApi;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.concurrent.CompletableFuture.supplyAsync;
/**
* Provide JPA operations running inside of a thread pool sized to the connection pool
*/
public class JPAPersonRepository implements PersonRepository {
private final JPAApi jpaApi;
private final DatabaseExecutionContext executionContext;
@Inject
public JPAPersonRepository(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
this.jpaApi = jpaApi;
this.executionContext = executionContext;
}
@Override
public CompletionStage<Person> add(Person person) {
return supplyAsync(() -> wrap(em -> insert(em, person)), executionContext);
}
@Override
public CompletionStage<Stream<Person>> list() {
return supplyAsync(() -> wrap(em -> list(em)), executionContext);
}
private <T> T wrap(Function<EntityManager, T> function) {
return jpaApi.withTransaction(function);
}
private Person insert(EntityManager em, Person person) {
em.persist(person);
return person;
}
private Stream<Person> list(EntityManager em) {
List<Person> persons = em.createQuery("select p from Person p", Person.class).getResultList();
return persons.stream();
}
}