DEV Community

aristides villarreal
aristides villarreal

Posted on

Helidon application development with MongoDB and Jmoordbcore

Below is a simple example of a Java application running on Helidon 4.0.0 and Java 21 with a MongoDB database, in which we will use Jmoordbcore framework.

Perform the following steps:

Below is a simple example of a Java application running on Helidon 4.0.0 and Java 21 with a MongoDB database, in which we use the Jmoordbcore framework.

Please follow the steps below:

Download Java 21 version 21, in this case we will use https://adoptium.net/es/, unzip it and install it on your operating system.

Go to the Helidon Starter site to create the project [https://helidon.io/starter/
Fill in the information and download the file.
Once you have downloaded the zipped file, unzip it, open it in your preferred IDE and add the value microprofile-config.properties to the file.

mongodb.uri=mongodb://localhost:27017
#-- Configuration database
mongodb.jmoordb= configurationjmoordbdb
#-- Database
mongodb.database=exampledb
mongodb.database1=testdb
Enter fullscreen mode Exit fullscreen mode

Now edit the pom.xml file and add the repository and dependencies.

 <repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>
 <dependency>
            <groupId>com.avbravo.jmoordb.core.processor</groupId>
            <artifactId>jmoordb-core</artifactId>
            <version>1.0.0.b-6.100</version>
        </dependency>
Enter fullscreen mode Exit fullscreen mode

Create an entity called student

Entity()
public class Student {

    @Id
    private String idstudent;
    @Column
    private String name;

    @Column
    private Integer age;
...
}
Enter fullscreen mode Exit fullscreen mode

Create a repository

@Repository(entity=Student.class)
public interface StudentRepository extends CrudRepository<Student, String>{


    @Find
    public List<Student> findByName(String name);
    @Find
    public List<Student> findByAgeGreaterThanPagination(Integer age, Pagination pagination);
}

Enter fullscreen mode Exit fullscreen mode

Create a producer class

@ApplicationScoped
@DateSupport(jakartaSource = JakartaSource.JAKARTA)
public class MongoDBProducer implements Serializable {



    @Inject
    private Config config;
    @Inject
    @ConfigProperty(name = "mongodb.uri")
    private String mongodburi;

    @Produce
    @ApplicationScoped
    public MongoClient mongoClient mongoClient() {


        MongoClient mongoClient = MongoClients.create(mongodburi);
       return mongoClient;

    }

    public void close(@Disposes final MongoClient mongoClient mongoClient) {


        mongoClient.close();
    }

}
Enter fullscreen mode Exit fullscreen mode

Create a controller to generate the endpoints

@Path("estudiante")
public class EstudianteController {



    @Inject
    EstudianteRepository estudianteRepository;


    @GET
    @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})

    public List<Estudiante> findAll() {


        return estudianteRepository.findAll();
    }

    @GET
    @Path("{idestudiante}")
    public Estudiante findByIdestudiante(@PathParam("idestudiante") String idestudiante) {


        return estudianteRepository.findByPk(idestudiante).orElseThrow(


                () -> new WebApplicationException("No hay estudiante con idestudiante " + idestudiante, Response.Status.NOT_FOUND));

    }

    @POST
    public Response save(@RequestBody(description = "Crea un nuevo estudiante.", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Estudiante.class))) Estudiante estudiante) {



        return Response.status(Response.Status.CREATED).entity(estudianteRepository.save(estudiante)).build();
    }

    @PUT
    public Response update(


            @RequestBody(description = "Crea un nuevo estudiante.", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Estudiante.class))) Estudiante estudiante) {



        return Response.status(Response.Status.CREATED).entity(estudianteRepository.update(estudiante)).build();
    }

    @DELETE
    @Path("{idestudiante}")
    public Response delete(@PathParam("idestudiante") String idestudiante) {


        estudianteRepository.deleteByPk(idestudiante);
        return Response.status(Response.Status.NO_CONTENT).build();
 @Path("estudiante")
public class EstudianteController {



    @Inject
    EstudianteRepository estudianteRepository;


    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

    public List<Estudiante> findAll() {


        return estudianteRepository.findAll();
    }

    @GET
    @Path("{idestudiante}")
    public Estudiante findByIdestudiante(@PathParam("idestudiante") String idestudiante) {


        return estudianteRepository.findByPk(idestudiante).orElseThrow(


                () -> new WebApplicationException("No hay estudiante con idestudiante " + idestudiante, Response.Status.NOT_FOUND));

    }

    @POST
    public Response save(@RequestBody(description = "Crea un nuevo estudiante.", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Estudiante.class))) Estudiante estudiante) {



        return Response.status(Response.Status.CREATED).entity(estudianteRepository.save(estudiante)).build();
    }

    @PUT
    public Response update(


            @RequestBody(description = "Crea un nuevo estudiante.", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Estudiante.class))) Estudiante estudiante) {



        return Response.status(Response.Status.CREATED).entity(estudianteRepository.update(estudiante)).build();
    }

    @DELETE
    @Path("{idestudiante}")
    public Response delete(@PathParam("idestudiante") String idestudiante) {


        estudianteRepository.deleteByPk(idestudiante);
        return Response.status(Response.Status.NO_CONTENT).build();
    }

    @GET
    @Path("findbynombre")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Estudiante> findByNombre(@QueryParam("nombre") String nombre) {


        return estudianteRepository.findByNombre(nombre);

    }

}   }

    @GET
    @Path("findbynombre")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Estudiante> findByNombre(@QueryParam("nombre") String nombre) {


        return estudianteRepository.findByNombre(nombre);

    }

}
Enter fullscreen mode Exit fullscreen mode

In this way we created a simple project in Helidon that uses the Microprofile specifications.

Build and execute the project


mvn clean verify

java -jar target/capitulo16.jar 

Enter fullscreen mode Exit fullscreen mode

Consult the endpoint via

http://localhost:8080/estudiante

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay