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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

AWS GenAI Live!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️