Saving the Superheros - Micronaut JDBC Data Access

Saving the Superheros - Micronaut JDBC Data Access

Micronaut JDBC Data in action

In our series we have created an application which can call superheroes to save the world. But every time we call the superheroes we generate new ones on the fly using Faker , it's good for show of but we need to create real superheroes who can live for longer that a HTTP call. If you have not followed our tutorials yet , you can look them

Source code of this tutorial: https://github.com/CODINGSAINT/super-heroes/tree/02MICRONAUT_DATABASE

To Save our superheroes we need a home for them to live. We will give them a home and store them. We give them a base to live in called H2 Database. Let us start adding the dependency for H2 database and the JDBC . Add following in your pom file

<dependency> 
    <groupId>io.micronaut.data</groupId>
    <artifactId>micronaut-data-jdbc</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> 
    <groupId>io.micronaut.sql</groupId>
    <artifactId>micronaut-jdbc-hikari</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> 
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

Since we have to process annotations at compile time , we will add following inside annotationProcessorPaths tag.

<path> 
    <groupId>io.micronaut.data</groupId>
    <artifactId>micronaut-data-processor</artifactId>
   <version>${micronaut.version}</version>
</path>

Let us create a dataSource . We will add following properties for data source

datasources:
  default:
    url: ${JDBC_URL:`jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE`}
    username: ${JDBC_USER:sa}
    password: ${JDBC_PASSWORD:""}
    driverClassName: ${JDBC_DRIVER:org.h2.Driver}

Now we have added dataSource . let us create a Data object for defining Superheroes and save them to database.

@MappedEntity
public record Superhero(@Id @GeneratedValue @Nullable Long id,
                        String name,
                        String prefix,
                        String suffix,
                        String power) {
}

We will not create Repository to facilitate the database operation. We will create an interface named SuperheroRepository and extend `PageableRepository from micronaut.

@JdbcRepository(dialect = Dialect.H2)
public interface SuperheroRepository extends PageableRepository<Superhero,Long> {

Now we can inject this SuperheroRepository to our SuperHeroController. We will also add ExecuteOn annotation over controller .

@Controller
@ExecuteOn(TaskExecutors.IO)
public class SuperHeroController {
    private static final Logger logger = LoggerFactory.getLogger(SuperHeroController.class);
    protected SuperheroRepository superheroRepository;

    SuperHeroController(SuperheroRepository superheroRepository) {
        this.superheroRepository = superheroRepository;
    }
}

Inside the controller we will add the method to save, update , retrieve and delete.

Saving the superheroes

Below is a sample code for saving the super hero along with a private utility method URI to generate URLs

 @Post("superhero")
    public HttpResponse<Superhero> save(@Valid Superhero superhero) {
        logger.info("Saving new Superhero {}", superhero);
        var superHero = superheroRepository.save(superhero);
        return HttpResponse.created(superHero)
                .headers(headers -> headers.location(URI("/superhero/" + "" + superHero.id())));

    }
private URI URI(String url) {
        URI uri = null;
        try {
            uri = new URI(url);
            return uri;
        } catch (URISyntaxException e) {
            logger.error("Error while creating URL {}",e);
        }
        return uri;
    }

Retrieving Superheroes

Below is a sample code to retrieve superheroes by id.

@Get("superhero/{id}")
    public Optional<Superhero> get(Long id) {
        return superheroRepository.findById(id);
    }

Updating Superhero

@Put("superhero")
    public HttpResponse update(@Body @Valid Superhero superhero) {
        superheroRepository.update(superhero);
        return HttpResponse
                .noContent()
                .headers(headers ->
                        headers.location(URI("/superhero/" + "" + superhero.id())));
    }

Deleting Superhero by id

 @Delete("superhero/{id}")
    @Status(HttpStatus.NO_CONTENT)
    public void delete(Long id) {
        superheroRepository.deleteById(id);
    }

In this article we saw how to perform CRUD operations with micronaut .


If you like my articles you can support me by sharing the articles with your friends, twitter, facebook or any other social media. You can also buy me a coffee output-onlinepngtools.png

Did you find this article valuable?

Support Kumar Pallav by becoming a sponsor. Any amount is appreciated!