Micronaut in the Cloud: PostgreSQL with JPA
In the second of this series on deploying Micronaut to the cloud, we take a look at building the Micronaut app with JPA with PostgreSQL.
Join the DZone community and get the full member experience.
Join For FreeMicronaut is an open-source, JVM-based framework for building full-stack, modular, easily testable microservice and serverless applications.
Unlike reflection-based IoC frameworks that load and cache reflection data for every single field, method, and constructor in your code, with Micronaut, your application startup time and memory consumption are not bound to the size of your codebase. Micronaut's cloud support is built right in, including support for common discovery services, distributed tracing tools, and cloud runtimes.
The tutorial of the second tutorial about Micronaut in the cloud we'll deploy an application with JPA integrated with PostgreSQL.
The first step is to create the application itself, and Micronaut has proper documentation. You have the start code link where you can define the dependencies that you need to write your application.
If you want to run a PostgreSQL locally, a good option might be Docker, which you can run with the command below:
x
docker run --ulimit memlock=-1:-1 -it --rm=true --memory-swappiness=0 --name micronaut_test -e POSTGRES_USER=micronaut -e POSTGRES_PASSWORD=micronaut -e POSTGRES_DB=micronaut -p 5432:5432 postgres:10.5
We need to configure the application to run locally to test it.
xxxxxxxxxx
micronaut
application
name jpa
datasources
default
url $ JDBC_URL `jdbc postgresql //localhost 5432/micronaut`
driverClassName org.postgresql.Driver
username $ JDBC_USER micronaut
password $ JDBC_PASSWORD micronaut
jpa.default.properties.hibernate.hbm2ddl.auto update
The infrastructure code is ready; the next step is to create the application itself. In this sample, we'll create a small rest-application to store heroes names. Therefore, we'll create a Hero entity.
x
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Objects;
public class Hero {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Hero hero = (Hero) o;
return Objects.equals(id, hero.id);
}
public int hashCode() {
return Objects.hashCode(id);
}
public String toString() {
return "Hero{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
The service layer connects the database to an Entity.
To mark the transaction demarcations, we use the Java EE 7 javax.transaction.Transactional annotation.
x
import io.micronaut.transaction.annotation.ReadOnly;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
public class HeroService {
private final EntityManager entityManager;
public HeroService(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Optional<Hero> findById( Long id) {
return Optional.ofNullable(entityManager.find(Hero.class, id));
}
public Hero save(Hero hero) {
entityManager.persist(hero);
return hero;
}
public List<Hero> findAll() {
TypedQuery<Hero> query = entityManager.createQuery("SELECT h FROM Hero as h order by h.name", Hero.class);
return query.getResultList();
}
public void deleteById( Long id) {
findById(id).ifPresent(entityManager::remove);
}
}
The last step is to create a resource where the client can do the request and then the CRUD.
xxxxxxxxxx
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Delete;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.scheduling.annotation.ExecuteOn;
import javax.validation.Valid;
import java.util.List;
TaskExecutors.IO) (
"heroes") (
public class HeroController {
private final HeroService service;
public HeroController(HeroService service) {
this.service = service;
}
"/{id}") (
public Hero show(Long id) {
return service.findById(id).orElse(null);
}
public List<Hero> findAll() {
return service.findAll();
}
public HttpResponse<Hero> save( Hero hero) {
return HttpResponse.created(service.save(hero));
}
"/{id}") (
public HttpResponse delete(Long id) {
service.deleteById(id);
return HttpResponse.noContent();
}
}
The application is ready to go, and you can run the test the application. The next step is to move to the cloud with Platform.sh.
- To move your application to the cloud, briefly, you need three files:
xxxxxxxxxx
"https://{default}/":
type upstream
upstream"app:http"
"https://www.{default}/"
type redirect
to"https://{default}/"
- Platform.sh allows you to completely define and configure the topology and services you want to use on your project.
xxxxxxxxxx
db
type postgresql11
disk512
- One containers (.platform.app.yaml). You control your application and the way it will be built and deployed on Platform.sh via a single configuration file. On this application, we allow the relationship between the PostgreSQL database and the application. So, our application container will have access to see the PostgreSQL container. Also, we'll overwrite the local configuration to use in the cloud to Platform.sh.
xxxxxxxxxx
name app
type"java:11"
disk1024
hooks
build mvn clean package -DskipTests
relationships
database"db:postgresql"
web
commands
start java -jar $JAVA_OPTS target/jpa-0.1.jar
To simplify the application file, we'll use Shell variables int the .environment
file.
xxxxxxxxxx
export JDBC_HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].host"`
export JDBC_PORT=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].port"`
export JDBC_PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].password"`
export JDBC_USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].username"`
export DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].path"`
export JDBC_URL=jdbc:postgresql://${JDBC_HOST}:${JDBC_PORT}/${DATABASE}
export JAVA_MEMORY=-Xmx$(jq .info.limits.memory /run/config.json)m
export JAVA_OPTS="$JAVA_MEMORY -XX:+ExitOnOutOfMemoryError"
The application is now ready, so it’s time to move it to the cloud with Platform.sh using the following steps:
- Create a new free trial account.
- Sign up with a new user and password, or login using a current GitHub, Bitbucket, or Google account. If you use a third-party login, you’ll be able to set a password for your Platform.sh account later.
- Select the region of the world where your site should live.
- Select the blank template.
You have the option to either integrate to GitHub, GitLab, or Platform.sh will provide to you. Finally, push to the remote repository.
Done! We have a simple and nice Micronaut application ready to go to the cloud.
Opinions expressed by DZone contributors are their own.
Comments