an idea of general service for the persistence context


@Stateless
public class PersistenceContextService {

    @PersistenceContext
    private EntityManager entityManager;

    public void accept(final Consumer<EntityManager> consumer) {
        consumer.accept(entityManager);
    }

    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.

@Path("/people")
public class PeopleResource {

    @Inject
    private PersistenceContextService service;

    @POST
    @Consumes({MediaType.APPLICATION_JSON})
    public Response create(final Person person) {
        service.accept(em -> em.persist(person));
        return Response.created(URI.create(person.getId()).build();
    }

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s