During my first steps in learning Google Guice, I was not able to find a full, working example of a servlet application that would use the Guice PersistService to interact with an underlying DB. After reading a few available articles and doing many, many experiments I was able to come up with a minimalistic application that I hope presents this use case well.
The project builds a dockerized Postgres DB with a toy table Employee in which the sole record is updated every time the PUT endpoint on the servlet is executed. The table and the record does not have any meaning - it is just there so that we can see the updates of the timestamp in the record.
I found that the top level service method called by the servlet must have the @Transactional annotation for this to work. Putting the annotation on a nested method (like updateTimestamp) instead will not result in DB update.
Other than that, the other pieces of this small web service are the minimum that is needed to make it work.
- mvn clean install
- docker-compose -f docker-postgresql.yml
- java -jar guice-servlet-db-example-0.0.1-jar-with-dependencies.jar
- Use the rest API by executing curl -X PUT http://localhost:8080/employee
- Note updates on the record in the DB
- Note that the Entity Manager changes with each request