{{announcement.body}}
{{announcement.title}}

Micronaut in the Cloud: PostgreSQL with JPA

DZone 's Guide to

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.

· Java Zone ·
Free Resource

Micronaut 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:

Shell
 




x


1
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.

YAML
 




xxxxxxxxxx
1
11


 
1
micronaut:
2
  application:
3
    name: jpa
4
datasources:
5
  default:
6
    url: ${JDBC_URL:`jdbc:postgresql://localhost:5432/micronaut`}
7
    driverClassName: org.postgresql.Driver
8
    username: ${JDBC_USER:micronaut}
9
    password: ${JDBC_PASSWORD:micronaut}
10
jpa.default.properties.hibernate.hbm2ddl.auto: update
11
 
          



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.

Java
 




x


 
1
import javax.persistence.Column;
2
import javax.persistence.Entity;
3
import javax.persistence.GeneratedValue;
4
import javax.persistence.Id;
5
import java.util.Objects;
6
 
          
7
@Entity
8
public class Hero {
9
 
          
10
    @Id
11
    @GeneratedValue
12
    private Long id;
13
 
          
14
    @Column
15
    private String name;
16
 
          
17
    public Long getId() {
18
        return id;
19
    }
20
 
          
21
    public void setId(Long id) {
22
        this.id = id;
23
    }
24
 
          
25
    public String getName() {
26
        return name;
27
    }
28
 
          
29
    public void setName(String name) {
30
        this.name = name;
31
    }
32
 
          
33
 
          
34
    @Override
35
    public boolean equals(Object o) {
36
        if (this == o) {
37
            return true;
38
        }
39
        if (o == null || getClass() != o.getClass()) {
40
            return false;
41
        }
42
        Hero hero = (Hero) o;
43
        return Objects.equals(id, hero.id);
44
    }
45
 
          
46
    @Override
47
    public int hashCode() {
48
        return Objects.hashCode(id);
49
    }
50
 
          
51
    @Override
52
    public String toString() {
53
        return "Hero{" +
54
                "id=" + id +
55
                ", name='" + name + '\'' +
56
                '}';
57
    }
58
}
59
 
          



The service layer connects the database to an Entity.

To mark the transaction demarcations, we use the Java EE 7 javax.transaction.Transactional annotation.

Java
 




x


 
1
import io.micronaut.transaction.annotation.ReadOnly;
2
 
          
3
import javax.inject.Singleton;
4
import javax.persistence.EntityManager;
5
import javax.persistence.TypedQuery;
6
import javax.transaction.Transactional;
7
import javax.validation.constraints.NotNull;
8
import java.util.List;
9
import java.util.Optional;
10
 
          
11
@Singleton
12
public class HeroService {
13
 
          
14
    private final EntityManager entityManager;
15
 
          
16
    public HeroService(EntityManager entityManager) {
17
        this.entityManager = entityManager;
18
    }
19
 
          
20
    @ReadOnly
21
    public Optional<Hero> findById(@NotNull Long id) {
22
        return Optional.ofNullable(entityManager.find(Hero.class, id));
23
    }
24
 
          
25
    @Transactional
26
    public Hero save(Hero hero) {
27
        entityManager.persist(hero);
28
        return hero;
29
    }
30
 
          
31
    @ReadOnly
32
    public List<Hero> findAll() {
33
        TypedQuery<Hero> query = entityManager.createQuery("SELECT h FROM Hero as h order by h.name", Hero.class);
34
        return query.getResultList();
35
    }
36
 
          
37
    @Transactional
38
    public void deleteById(@NotNull Long id) {
39
        findById(id).ifPresent(entityManager::remove);
40
    }
41
 
          
42
}
43
 
          



The last step is to create a resource where the client can do the request and then the CRUD.

Java
 




xxxxxxxxxx
1
44


 
1
import io.micronaut.http.HttpResponse;
2
import io.micronaut.http.annotation.Body;
3
import io.micronaut.http.annotation.Controller;
4
import io.micronaut.http.annotation.Delete;
5
import io.micronaut.http.annotation.Get;
6
import io.micronaut.http.annotation.Post;
7
import io.micronaut.scheduling.TaskExecutors;
8
import io.micronaut.scheduling.annotation.ExecuteOn;
9
 
          
10
import javax.validation.Valid;
11
import java.util.List;
12
 
          
13
@ExecuteOn(TaskExecutors.IO)
14
@Controller("heroes")
15
public class HeroController {
16
 
          
17
    private final HeroService service;
18
 
          
19
    public HeroController(HeroService service) {
20
        this.service = service;
21
    }
22
 
          
23
    @Get("/{id}")
24
    public Hero show(Long id) {
25
        return service.findById(id).orElse(null);
26
    }
27
 
          
28
    @Get
29
    public List<Hero> findAll() {
30
        return service.findAll();
31
    }
32
 
          
33
    @Post
34
    public HttpResponse<Hero> save(@Body @Valid Hero hero) {
35
        return HttpResponse.created(service.save(hero));
36
    }
37
 
          
38
    @Delete("/{id}")
39
    public HttpResponse delete(Long id) {
40
        service.deleteById(id);
41
        return HttpResponse.noContent();
42
    }
43
}
44
 
          



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:
YAML
 




xxxxxxxxxx
1


 
1
"https://{default}/":
2
  type: upstream
3
  upstream: "app:http"
4
 
          
5
"https://www.{default}/":
6
  type: redirect
7
  to: "https://{default}/"
8
 
          



YAML
 




xxxxxxxxxx
1


 
1
db:
2
  type: postgresql:11
3
  disk: 512



  • 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.
YAML
 




xxxxxxxxxx
1
10


 
1
name: app
2
type: "java:11"
3
disk: 1024
4
hooks:
5
    build: mvn clean package -DskipTests
6
relationships:
7
    database: "db:postgresql"
8
web:
9
    commands:
10
        start: java -jar $JAVA_OPTS target/jpa-0.1.jar



To simplify the application file, we'll use Shell variables int the  .environment  file.

Shell
 




xxxxxxxxxx
1


 
1
export JDBC_HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].host"`
2
export JDBC_PORT=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].port"`
3
export JDBC_PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].password"`
4
export JDBC_USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].username"`
5
export DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].path"`
6
export JDBC_URL=jdbc:postgresql://${JDBC_HOST}:${JDBC_PORT}/${DATABASE}
7
export JAVA_MEMORY=-Xmx$(jq .info.limits.memory /run/config.json)m
8
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.




Topics:
cloud, java, micronaut, paas, platform.sh, postgresql

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}