Skip to content

About

A working example on how to use the Eclipse JNoSQL REST utility

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

4 Commits

Folders and files

Repository files navigation

REST Repository: Beer API with Eclipse JNoSQL, MongoDB, and GlassFish

REST Repository, powered by Eclipse JNoSQL, exposes Jakarta Data repository methods as Jakarta REST endpoints at compile time. This example uses a Beer entity stored in MongoDB, a custom Jakarta Data repository, and Eclipse GlassFish 9.0.0-M4 (Jakarta EE 12 milestone). REST endpoints are generated from the repository; no handwritten resource controller is required.

Technology

  • Java 21 and GlassFish 9.0.0-M4 (Jakarta EE 12 milestone, as configured in pom.xml).
  • MongoDB 8.3, launched locally with Docker Compose.
  • Jakarta NoSQL, Jakarta Data, and Eclipse JNoSQL for persistence.
  • REST Repository (jnosql-rest-api and jnosql-rest-processor) for generated Jakarta REST resources.
  • MapStruct for generated entity/DTO conversions, enabled by @RestDTO.

Project versions: The supplied pom.xml targets GlassFish 9.0.0-M4, Jakarta Data and NoSQL 1.1.0-M4, CDI 5.0.0, JNoSQL 2.0.0-M1, REST Repository 2.0.0-SNAPSHOT, and MapStruct 1.6.3. Maven milestone/SNAPSHOT dependencies must be available locally or from configured repositories.

Project layout

.
├── compose.yaml
├── pom.xml                                # Supplied Maven WAR project
└── src/main/
    ├── java/org/redlich/data/
    │   ├── Beer.java
    │   ├── BeerRepository.java
    │   └── RestApplication.java
    └── resources/META-INF/
        └── microprofile-config.properties

1. Start MongoDB

docker compose up -d
docker compose ps

The Compose service listens on localhost:27017, persists data in the mongodb-data volume, and includes a MongoDB health check.

Inspect the connection:

docker compose exec mongodb mongosh --quiet --eval 'db.adminCommand({ ping: 1 })'

Stop without deleting the data:

docker compose down

To remove all local demo data, run docker compose down -v only if you intentionally want to delete the MongoDB volume.

2. Configure Eclipse JNoSQL

The project already includes src/main/resources/META-INF/microprofile-config.properties with these settings:

jnosql.mongodb.host=localhost:27017
jnosql.document.database=beers_db

These values assume GlassFish runs on your host machine. If GlassFish runs in another Docker Compose service on the same network, the MongoDB hostname would instead be mongodb:27017.

The supplied pom.xml already declares jnosql-mongodb 2.0.0-M1, jnosql-rest-api 2.0.0-SNAPSHOT, MapStruct 1.6.3, and both annotation processors. It also declares Jakarta Data and Jakarta NoSQL 1.1.0-M4 as provided, and CDI 5.0.0 as provided. Keep these aligned with GlassFish 9.0.0-M4; do not replace them with a Jakarta EE 11 API bundle. The POM excludes selected JNoSQL transitive components on the assumption that GlassFish provides them; verify these modules are present in the target server and compatible at runtime.

Relevant reference documentation:

3. Understand the repository

The sample Beer entity contains id (int), name, brewer, type, and abv (double). It uses @Entity, @Id, and @Column for NoSQL mapping.

The repository is a custom Jakarta Data repository, not a BasicRepository or CrudRepository subtype. The example below reflects the latest findById change (without method-level @Path):

@Repository
@RestRepository(path = "/beers")
@RestDTO
public interface BeerRepository {

    @Insert
    Beer insert(Beer beer);

    Optional<Beer> findById(int id);

    @Delete
    void delete(int id);

    @Find
    @OrderBy("id")
    @Path("")
    Page<Beer> findAll(PageRequest request);
}

@RestRepository generates the HTTP layer using repository operations. @RestDTO enables DTO generation and MapStruct conversion. In particular, @Path("") explicitly maps the custom paginated findAll() operation to the collection root, rather than a /findAll suffix.

The supplied RestApplication declares the JAX-RS base path:

@ApplicationPath("/api")
public class RestApplication extends Application {
}

Generated endpoints

With these repository signatures, the intended routes are (confirm the inferred findById route in the generated source):

Method Path Repository operation
POST /api/beers insert(Beer)
GET /api/beers/{id} findById(int)
DELETE /api/beers/{id} delete(int)
GET /api/beers?offset=0&size=20 findAll(PageRequest)

These paths are relative to the deployed application's context root. Actual HTTP status codes and serialized payload wrappers depend on the generated REST implementation.

Mapping note: The supplied Beer class has public getters but no setters, and its parameterized constructor is private. Verify that JNoSQL and MapStruct can construct and populate it for insert/DTO conversion. If not, add an appropriate writable entity model or mapping strategy before expecting POST to persist supplied attributes. The default constructor currently initializes placeholder values.

4. Quick start: build and run with Maven (GlassFish 9.0.0-M4)

After changing repository annotations, always perform a clean Maven build so the JNoSQL REST processor regenerates the resource and DTO types. Do not deploy a previously generated WAR.

docker compose up -d
mvn clean package embedded-glassfish:run

The second command is the recommended way to build, deploy, and run this demo. It executes Maven clean and package before the embedded GlassFish run goal, removing stale generated resource classes. Leave that terminal running while exercising the API and use Ctrl+C to exit.

The embedded API root is expected at http://localhost:8080/api/beers once deployment succeeds. If Jersey rejects the application resource model during startup, inspect the section on Jersey resource discovery below; a successful Maven package alone does not mean the REST application deployed.

Build and deployment details

The supplied pom.xml configures the GlassFish 9.0.0-M4 milestone using the embedded-glassfish-maven-plugin (plugin version 8.1). The project's Java release is 21, packaging is WAR, its artifact/final name is jakarta-data-age, and the embedded plugin is configured for port 8080 and context root /.

This targets a Jakarta EE 12 milestone environment, not GlassFish 8 / Jakarta EE 11. The POM pins individual milestone APIs rather than a final Jakarta EE 12 API bundle. Milestone and SNAPSHOT artifacts may need compatible repositories or local builds.

Build using the supplied POM:

mvn clean package

This should produce:

target/jakarta-data-age.war

Embedded GlassFish command details

The existing Maven POM already configures org.glassfish.embedded:embedded-glassfish-maven-plugin:8.1, which supports the run goal. Its configured GlassFish server version is 9.0.0-M4, with port 8080 and context root /.

From the project directory, run:

docker compose up -d
mvn clean package embedded-glassfish:run

This builds the WAR, starts embedded GlassFish, and deploys the application. The Maven process stays running; press Ctrl+C to stop it. The expected endpoint is:

http://localhost:8080/api/beers

If Maven cannot resolve the run prefix, use the fully qualified goal:

mvn clean package org.glassfish.embedded:embedded-glassfish-maven-plugin:8.1:run

The pom.xml also defines an it profile for Maven integration tests, with server start/deploy and undeploy/stop lifecycle executions:

mvn clean verify -Pit

That command is for the integration-test lifecycle, not for keeping the demo server available for manual cURL calls. As with all milestone/SNAPSHOT combinations, first verify that the required artifacts are resolvable; these commands were not executed as part of this README update.

Standalone GlassFish 9.0.0-M4

For a standalone GlassFish 9.0.0-M4 installation, start the domain and deploy the WAR using the actual project artifact name:

$GLASSFISH_HOME/bin/asadmin start-domain
$GLASSFISH_HOME/bin/asadmin deploy --force=true \
  --contextroot jakarta-data-age target/jakarta-data-age.war

The API URL for that deployment is:

http://localhost:8080/jakarta-data-age/api/beers

Use the correct URL for your chosen deployment mode; the POM's embedded-plugin context root does not automatically apply to standalone deployments.

5. Test the API with cURL

Choose the base URL for the deployment you are running. Embedded GlassFish (the Maven quick start above):

BASE_URL=http://localhost:8080/api/beers

For standalone GlassFish deployed with the context root in Section 4, use:

BASE_URL=http://localhost:8080/jakarta-data-age/api/beers

Create — POST

curl -i -X POST "$BASE_URL" \
  -H 'Content-Type: application/json' \
  -d '{"id":1,"name":"Pale Ale","brewer":"Example Brewery","type":"Ale","abv":5.2}'

The provided Beer entity has getters but no setters and a private parameterized constructor. Because @RestDTO uses MapStruct, verify that request-to-entity mapping works before expecting this request to persist all submitted attributes. The generated BeerCreateRequest should also be checked for its exact fields.

Read one — GET

curl -i "$BASE_URL/1"

List with pagination — GET

curl -i "$BASE_URL?offset=0&size=20"

For the sample repository, @Find @Path("") Page<Beer> findAll(PageRequest) exposes this collection-root route. A paginated response contains paging metadata, not necessarily a bare JSON array.

Delete / remove a beer — DELETE

curl -i -X DELETE "$BASE_URL/1"

The repository's @Delete void delete(int id) is exposed at /beers/{id}. Use GET "$BASE_URL/1" afterwards to check whether the record is gone. HTTP DELETE is the operation for removing an individual beer; no separate remove HTTP method is needed.

Update a beer — PUT (requires a repository change)

The provided BeerRepository does not declare an update operation, so PUT /beers/1 is not currently generated. Do not expect this command to work until update support is enabled in the repository.

A straightforward supported approach is to use the standard Jakarta Data CrudRepository<Beer, Integer> with @RestRepository and @RestDTO (and adjust/remove custom declarations as appropriate). REST Repository's standard CRUD update generation in DTO mode uses a lookup by ID followed by DTO mapping and repository.update(entity), exposing PUT /beers/{id} when the entity is writable.

For example, the alternative repository definition below illustrates the relevant setup; it is not the repository currently included in this demo:

@Repository
@RestRepository(path = "/beers")
@RestDTO
public interface BeerRepository extends CrudRepository<Beer, Integer> {
}

After implementing and validating that repository change and ensuring the Beer entity supports updates, an example request would be:

curl -i -X PUT "$BASE_URL/1" \
  -H 'Content-Type: application/json' \
  -d '{"name":"Pale Ale","brewer":"Example Brewery","type":"IPA","abv":6.1}'

The generated BeerUpdateRequest governs the accepted fields. The ID is supplied by the URL; do not assume the request body can change it.

Why not just add @Update to the current custom repository? In the inspected REST processor, an @Update method accepting an entity is supported for a custom repository only without @RestDTO. With the current DTO annotation, the generated update route must follow the supported standard repository update path instead. Alternatively, remove @RestDTO and use a supported custom @Update method if that matches your design.

Remove the demo database (optional)

Stop MongoDB without losing the saved beers:

docker compose down

Remove MongoDB and delete the persisted demo data:

docker compose down -v

This deletes the named mongodb-data volume. Use it only when you want to reset the demo database.

Example beer representation

A successful single-beer response should contain the applicable attributes (subject to generated DTO mapping):

{
  "id": 1,
  "name": "Pale Ale",
  "brewer": "Example Brewery",
  "type": "Ale",
  "abv": 5.2
}

6. Troubleshooting

Jersey reports duplicate {id} subresource locators

An earlier GlassFish startup failed with ModelValidationException because Jersey discovered BeerRepository (the repository interface itself) as a REST resource. Multiple method-level @Path("{id}") declarations without HTTP-method annotations were interpreted as subresource locators. The generated BeerRepositoryResource already has the correct @GET, @DELETE, and @Path declarations; do not edit the generated Java file.

The current repository example omits @Path on findById, but retains @Path("{id}") on delete and @Path("") on paginated findAll. That may remove the original duplicate-locator error, but it does not by itself prove that Jersey will stop discovering the repository interface. If deployment continues to fail, inspect the actual generated resource and Jersey's resource registration; consider explicitly registering BeerRepositoryResource.class in RestApplication.getClasses() as a diagnostic, then re-run mvn clean package embedded-glassfish:run. Do not remove all @Path annotations without accounting for the intended routes.

  • MongoDB connection refused: Check docker compose ps, the database hostname, and jnosql.mongodb.host. localhost only works when GlassFish runs on the host.
  • No REST endpoint generated: Confirm the REST Repository annotation processor is configured and inspect Maven-generated sources.
  • DTO mapper unavailable: Ensure the MapStruct processor is configured and the generated mapper implementation is packaged or discovered by CDI.
  • Unexpected POST values: Check the Beer entity construction/mapping model; the supplied class exposes getters but not setters.
  • Jakarta API linkage errors: Avoid mixing incompatible Jakarta Data or other API versions from the server with copies packaged in the WAR.
  • Path not found: Confirm the context root (/ for the configured embedded server, /jakarta-data-age in the standalone deployment example), /api from RestApplication, and /beers from @RestRepository.

References

About

A working example on how to use the Eclipse JNoSQL REST utility

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages