Tagged: entitymanager

an idea of general service for the persistence context

public class PersistenceContextService {

    private EntityManager entityManager;

    public void accept(final Consumer<EntityManager> consumer) {

    public void accept(final BiConsumer<EntityManager, U> consumer
                       final U u) {
        consumer.accept(entityManager, u);

    public <R> R apply(final Function<EnityManager, R> function) {
        return function.apply(entityManager);

    public <U, R> R appply(final BiFunction<EntityManager, U, R> function
                           final U u) {
        return function.apply(entityManager, u);

And now we can do this.

public class PeopleResource {

    private PersistenceContextService service;

    public Response create(final Person person) {
        service.accept(em -> em.persist(person));
        return Response.created(URI.create(person.getId()).build();

    @Path("/{id: \\d}")
    public Person read(final long id) {
        return service.apply(em -> em.find(Person.class, id));