When I started learning Guice, I was not able to use the persistence feature of it: even though the official documentation provides some tips, there is no end-to-end example to demonstrate it. The thing I was looking for was a simple but complete flow where we have a method annotated with Guice's @Transactional and the method makes an update to a database using Guice's PersistService, without the need for the developer to programmatically commit the transaction or manage the EntityManager instance.
I started looking for the examples, but the result was very much similar - each article or Stackoverflow post had just some pieces of information, not enough on its own to present the full case.
After combining these pieces of information and doing lots of experiments, I was finally able to come up with a minimalist implementation of a servlet application that:
- uses Guice for dependency injection
- uses Guice for persistence / transaction management
- makes a simple update to a database (in this case, Postgres)
The code is available on Github: https://github.com/pgorak/guice-servlet-db-example
and the project includes a tiny, dockerized Postgres DB.
One interesting finding that I made was that Guice only really acts upon the @Transactional annotation, if it is provided in the top level method. If the annotation is not at the top level, but it is provided in another, downstream method that is called by the top level one, then it does not work. It seems strange and it appears to me as a shortcoming, compared to the same annotation in Spring. Accidentally, it turned out to be the same finding that Kohei Nozaki described in his blog: https://nozaki.me/roller/kyle/entry/testing-guice-persist-nested-transactional