Quarkus - Simplified MongoDB with Panache

MongoDB is a well known NoSQL Database that is widely used, but using its raw API can be cumbersome as you need to express your entities and your queries as a MongoDB Document.

MongoDB with Panache provides active record style entities (and repositories) like you have in Hibernate ORM with Panache and focuses on making your entities trivial and fun to write in Quarkus.

It is built on top of the MongoDB Client extension.

First: an example

Panache allows you to write your MongoDB entities like this:

  1. public class Person extends PanacheMongoEntity {
  2. public String name;
  3. public LocalDate birth;
  4. public Status status;
  5. public static Person findByName(String name){
  6. return find("name", name).firstResult();
  7. }
  8. public static List<Person> findAlive(){
  9. return list("status", Status.Alive);
  10. }
  11. public static void deleteLoics(){
  12. delete("name", "Loïc");
  13. }
  14. }

You have noticed how much more compact and readable the code is compared to using the MongoDB API? Does this look interesting? Read on!

the list() method might be surprising at first. It takes fragments of PanacheQL queries (subset of JPQL) and contextualizes the rest. That makes for very concise but yet readable code. MongoDB native queries are also supported.
what was described above is essentially the active record pattern, sometimes just called the entity pattern. MongoDB with Panache also allows for the use of the more classical repository pattern via PanacheMongoRepository.

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the mongodb-panache-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=mongodb-panache-quickstart \
  4. -DclassName="org.acme.mongodb.panache.PersonResource" \
  5. -Dpath="/persons" \
  6. -Dextensions="resteasy-jsonb,mongodb-panache"
  7. cd mongodb-panache-quickstart

This command generates a Maven structure importing the RESTEasy/JAX-RS, JSON-B and MongoDB with Panache extensions. After this, the quarkus-mongodb-panache extension has been added to your pom.xml.

If you don’t want to generate a new project, add the dependency in your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-mongodb-panache</artifactId>
  4. </dependency>

Setting up and configuring MongoDB with Panache

To get started:

  • add your settings in application.properties

  • Make your entities extend PanacheMongoEntity (optional if you are using the repository pattern)

  • Optionally, use the @MongoEntity annotation to specify the name of the collection, the name of the database or the name of the client.

Then add the relevant configuration properties in application.properties.

  1. # configure the MongoDB client for a replica set of two nodes
  2. quarkus.mongodb.connection-string = mongodb://mongo1:27017,mongo2:27017
  3. # mandatory if you don't specify the name of the database using @MongoEntity
  4. quarkus.mongodb.database = person

The quarkus.mongodb.database property will be used by MongoDB with Panache to determine the name of the database where your entities will be persisted (if not overridden by @MongoEntity).

The @MongoEntity annotation allows configuring:

  • the name of the client for multi-tenant application, see Multiple MongoDB Clients. Otherwise, the default client will be used.

  • the name of the database, otherwise, the quarkus.mongodb.database property will be used.

  • the name of the collection, otherwise the simple name of the class will be used.

For advanced configuration of the MongoDB client, you can follow the Configuring the MongoDB database guide.

Solution 1: using the active record pattern

Defining your entity

To define a Panache entity, simply extend PanacheMongoEntity and add your columns as public fields. You can add the @MongoEntity annotation to your entity if you need to customize the name of the collection, the database, or the client.

  1. @MongoEntity(collection="ThePerson")
  2. public class Person extends PanacheMongoEntity {
  3. public String name;
  4. // will be persisted as a 'birth' field in MongoDB
  5. @BsonProperty("birth")
  6. public LocalDate birthDate;
  7. public Status status;
  8. }
Annotating with @MongoEntity is optional. Here the entity will be stored in the ThePerson collection instead of the default Person collection.

MongoDB with Panache uses the PojoCodecProvider to map your entities to a MongoDB Document.

You will be allowed to use the following annotations to customize this mapping:

  • @BsonId: allows you to customize the ID field, see Custom IDs.

  • @BsonProperty: customize the serialized name of the field.

  • @BsonIgnore: ignore a field during the serialization.

If you need to write accessors, you can:

  1. public class Person extends PanacheMongoEntity {
  2. public String name;
  3. public LocalDate birth;
  4. public Status status;
  5. // return name as uppercase in the model
  6. public String getName(){
  7. return name.toUpperCase();
  8. }
  9. // store all names in lowercase in the DB
  10. public void setName(String name){
  11. this.name = name.toLowerCase();
  12. }
  13. }

And thanks to our field access rewrite, when your users read person.name they will actually call your getName() accessor, and similarly for field writes and the setter. This allows for proper encapsulation at runtime as all fields calls will be replaced by the corresponding getter/setter calls.

Most useful operations

Once you have written your entity, here are the most common operations you will be able to perform:

  1. // creating a person
  2. Person person = new Person();
  3. person.name = "Loïc";
  4. person.birth = LocalDate.of(1910, Month.FEBRUARY, 1);
  5. person.status = Status.Alive;
  6. // persist it
  7. person.persist();
  8. person.status = Status.Dead;
  9. // Your must call update() in order to send your entity modifications to MongoDB
  10. person.update();
  11. // delete it
  12. person.delete();
  13. // getting a list of all Person entities
  14. List<Person> allPersons = Person.listAll();
  15. // finding a specific person by ID
  16. person = Person.findById(personId);
  17. // finding a specific person by ID via an Optional
  18. Optional<Person> optional = Person.findByIdOptional(personId);
  19. person = optional.orElseThrow(() -> new NotFoundException());
  20. // finding all living persons
  21. List<Person> livingPersons = Person.list("status", Status.Alive);
  22. // counting all persons
  23. long countAll = Person.count();
  24. // counting all living persons
  25. long countAlive = Person.count("status", Status.Alive);
  26. // delete all living persons
  27. Person.delete("status", Status.Alive);
  28. // delete all persons
  29. Person.deleteAll();
  30. // delete by id
  31. boolean deleted = Person.deleteById(personId);
  32. // set the name of all living persons to 'Mortal'
  33. long updated = Person.update("name", "Mortal").where("status", Status.Alive);

All list methods have equivalent stream versions.

  1. Stream<Person> persons = Person.streamAll();
  2. List<String> namesButEmmanuels = persons
  3. .map(p -> p.name.toLowerCase() )
  4. .filter( n -> ! "emmanuel".equals(n) )
  5. .collect(Collectors.toList());
A persistOrUpdate() method exist that persist or update an entity in the database, it uses the upsert capability of MongoDB to do it in a single query.

Adding entity methods

Add custom queries on your entities inside the entities themselves. That way, you and your co-workers can find them easily, and queries are co-located with the object they operate on. Adding them as static methods in your entity class is the Panache Active Record way.

  1. public class Person extends PanacheMongoEntity {
  2. public String name;
  3. public LocalDate birth;
  4. public Status status;
  5. public static Person findByName(String name){
  6. return find("name", name).firstResult();
  7. }
  8. public static List<Person> findAlive(){
  9. return list("status", Status.Alive);
  10. }
  11. public static void deleteLoics(){
  12. delete("name", "Loïc");
  13. }
  14. }

Solution 2: using the repository pattern

Defining your entity

You can define your entity as regular POJO. You can add the @MongoEntity annotation to your entity if you need to customize the name of the collection, the database, or the client.

  1. @MongoEntity(collection="ThePerson")
  2. public class Person {
  3. public ObjectId id; // used by MongoDB for the _id field
  4. public String name;
  5. public LocalDate birth;
  6. public Status status;
  7. }
Annotating with @MongoEntity is optional. Here the entity will be stored in the ThePerson collection instead of the default Person collection.

MongoDB with Panache uses the PojoCodecProvider to map your entities to a MongoDB Document.

You will be allowed to use the following annotations to customize this mapping:

  • @BsonId: allows you to customize the ID field, see Custom IDs.

  • @BsonProperty: customize the serialized name of the field.

  • @BsonIgnore: ignore a field during the serialization.

You can use public fields or private fields with getters/setters. If you don’t want to manage the ID by yourself, you can make your entity extends PanacheMongoEntity.

Defining your repository

When using Repositories, you can get the exact same convenient methods as wit the active record pattern, injected in your Repository, by making them implements PanacheMongoRepository:

  1. @ApplicationScoped
  2. public class PersonRepository implements PanacheMongoRepository<Person> {
  3. // put your custom logic here as instance methods
  4. public Person findByName(String name){
  5. return find("name", name).firstResult();
  6. }
  7. public List<Person> findAlive(){
  8. return list("status", Status.Alive);
  9. }
  10. public void deleteLoics(){
  11. delete("name", "Loïc");
  12. }
  13. }

All the operations that are defined on PanacheMongoEntityBase are available on your repository, so using it is exactly the same as using the active record pattern, except you need to inject it:

  1. @Inject
  2. PersonRepository personRepository;
  3. @GET
  4. public long count(){
  5. return personRepository.count();
  6. }

Most useful operations

Once you have written your repository, here are the most common operations you will be able to perform:

  1. // creating a person
  2. Person person = new Person();
  3. person.name = "Loïc";
  4. person.birth = LocalDate.of(1910, Month.FEBRUARY, 1);
  5. person.status = Status.Alive;
  6. // persist it
  7. personRepository.persist(person);
  8. person.status = Status.Dead;
  9. // Your must call update() in order to send your entity modifications to MongoDB
  10. personRepository.update(person);
  11. // delete it
  12. personRepository.delete(person);
  13. // getting a list of all Person entities
  14. List<Person> allPersons = personRepository.listAll();
  15. // finding a specific person by ID
  16. person = personRepository.findById(personId);
  17. // finding a specific person by ID via an Optional
  18. Optional<Person> optional = personRepository.findByIdOptional(personId);
  19. person = optional.orElseThrow(() -> new NotFoundException());
  20. // finding all living persons
  21. List<Person> livingPersons = personRepository.list("status", Status.Alive);
  22. // counting all persons
  23. long countAll = personRepository.count();
  24. // counting all living persons
  25. long countAlive = personRepository.count("status", Status.Alive);
  26. // delete all living persons
  27. personRepository.delete("status", Status.Alive);
  28. // delete all persons
  29. personRepository.deleteAll();
  30. // delete by id
  31. boolean deleted = personRepository.deleteById(personId);
  32. // set the name of all living persons to 'Mortal'
  33. long updated = personRepository.update("name", "Mortal").where("status", Status.Alive);

All list methods have equivalent stream versions.

  1. Stream<Person> persons = personRepository.streamAll();
  2. List<String> namesButEmmanuels = persons
  3. .map(p -> p.name.toLowerCase() )
  4. .filter( n -> ! "emmanuel".equals(n) )
  5. .collect(Collectors.toList());
A persistOrUpdate() method exist that persist or update an entity in the database, it uses the upsert capability of MongoDB to do it in a single query.
The rest of the documentation show usages based on the active record pattern only, but keep in mind that they can be performed with the repository pattern as well. The repository pattern examples have been omitted for brevity.

Advanced Query

Paging

You should only use list and stream methods if your collection contains small enough data sets. For larger data sets you can use the find method equivalents, which return a PanacheQuery on which you can do paging:

  1. // create a query for all living persons
  2. PanacheQuery<Person> livingPersons = Person.find("status", Status.Alive);
  3. // make it use pages of 25 entries at a time
  4. livingPersons.page(Page.ofSize(25));
  5. // get the first page
  6. List<Person> firstPage = livingPersons.list();
  7. // get the second page
  8. List<Person> secondPage = livingPersons.nextPage().list();
  9. // get page 7
  10. List<Person> page7 = livingPersons.page(Page.of(7, 25)).list();
  11. // get the number of pages
  12. int numberOfPages = livingPersons.pageCount();
  13. // get the total number of entities returned by this query without paging
  14. int count = livingPersons.count();
  15. // and you can chain methods of course
  16. return Person.find("status", Status.Alive)
  17. .page(Page.ofSize(25))
  18. .nextPage()
  19. .stream()

The PanacheQuery type has many other methods to deal with paging and returning streams.

Using a range instead of pages

PanacheQuery also allows range-based queries.

  1. // create a query for all living persons
  2. PanacheQuery<Person> livingPersons = Person.find("status", Status.Alive);
  3. // make it use a range: start at index 0 until index 24 (inclusive).
  4. livingPersons.range(0, 24);
  5. // get the range
  6. List<Person> firstRange = livingPersons.list();
  7. // to get the next range, you need to call range again
  8. List<Person> secondRange = livingPersons.range(25, 49).list();

You cannot mix ranges and pages: if you use a range, all methods that depend on having a current page will throw an UnsupportedOperationException; you can switch back to paging using page(Page) or page(int, int).

Sorting

All methods accepting a query string also accept an optional Sort parameter, which allows you to abstract your sorting:

  1. List<Person> persons = Person.list(Sort.by("name").and("birth"));
  2. // and with more restrictions
  3. List<Person> persons = Person.list("status", Sort.by("name").and("birth"), Status.Alive);

The Sort class has plenty of methods for adding columns and specifying sort direction.

Simplified queries

Normally, MongoDB queries are of this form: {'firstname': 'John', 'lastname':'Doe'}, this is what we call MongoDB native queries.

You can use them if you want, but we also support what we call PanacheQL that can be seen as a subset of JPQL (or HQL) and allows you to easily express a query. MongoDB with Panache will then map it to a MongoDB native query.

If your query does not start with {, we will consider it a PanacheQL query:

  • <singlePropertyName> (and single parameter) which will expand to {'singleColumnName': '?1'}

  • <query> will expand to {<query>} where we will map the PanacheQL query to MongoDB native query form. We support the following operators that will be mapped to the corresponding MongoDB operators: ‘and’, ‘or’ ( mixing ‘and’ and ‘or’ is not currently supported), ‘=’, ‘>’, ‘>=’, ‘<’, ‘⇐’, ‘!=’, ‘is null’, ‘is not null’, and ‘like’ that is mapped to the MongoDB $regex operator (both String and JavaScript patterns are supported).

Here are some query examples:

  • firstname = ?1 and status = ?2 will be mapped to {'firstname': ?1, 'status': ?2}

  • amount > ?1 and firstname != ?2 will be mapped to {'amount': {'$gt': ?1}, 'firstname': {'$ne': ?2}}

  • lastname like ?1 will be mapped to {'lastname': {'$regex': ?1}}. Be careful that this will be MongoDB regex support and not SQL like pattern.

  • lastname is not null will be mapped to {'lastname':{'$exists': true}}

  • status in ?1 will be mapped to {'status':{$in: [?1]}}

We also handle some basic date type transformations: all fields of type Date, LocalDate, LocalDateTime or Instant will be mapped to the BSON Date using the ISODate type (UTC datetime). The MongoDB POJO codec doesn’t support ZonedDateTime and OffsetDateTime so you should convert them prior usage.

MongoDB with Panache also supports extended MongoDB queries by providing a Document query, this is supported by the find/list/stream/count/delete methods.

MongoDB with Panache offers operations to update multiple documents based on an update document and a query : Person.update("foo = ?1, bar = ?2", fooName, barName).where("name = ?1", name).

For these operations, you can express the update document the same way you express your queries, here are some examples:

  • <singlePropertyName> (and single parameter) which will expand to the update document {'$set' : {'singleColumnName': '?1'}}

  • firstname = ?1, status = ?2 will be mapped to the update document {'$set' : {'firstname': ?1, 'status': ?2}}

  • firstname = :firstname, status = :status will be mapped to the update document {'$set' : {'firstname': :firstname, 'status': :status}}

  • {'firstname' : ?1, 'status' : ?2} will be mapped to the update document {'$set' : {'firstname': ?1, 'status': ?2}}

  • {'firstname' : firstname, 'status' : :status} ` will be mapped to the update document {'$set' : {'firstname': :firstname, 'status': :status}}

Query parameters

You can pass query parameters, for both native and PanacheQL queries, by index (1-based) as shown below:

  1. Person.find("name = ?1 and status = ?2", "Loïc", Status.Alive);
  2. Person.find("{'name': ?1, 'status': ?2}", "Loïc", Status.Alive);

Or by name using a Map:

  1. Map<String, Object> params = new HashMap<>();
  2. params.put("name", "Loïc");
  3. params.put("status", Status.Alive);
  4. Person.find("name = :name and status = :status", params);
  5. Person.find("{'name': :name, 'status', :status}", params);

Or using the convenience class Parameters either as is or to build a Map:

  1. // generate a Map
  2. Person.find("name = :name and status = :status",
  3. Parameters.with("name", "Loïc").and("status", Status.Alive).map());
  4. // use it as-is
  5. Person.find("{'name': :name, 'status': :status}",
  6. Parameters.with("name", "Loïc").and("status", Status.Alive));

Every query operation accepts passing parameters by index (Object…​), or by name (Map<String,Object> or Parameters).

When you use query parameters, be careful that PanacheQL queries will refer to the Object parameters name but native queries will refer to MongoDB field names.

Imagine the following entity:

  1. public class Person extends PanacheMongoEntity {
  2. @BsonProperty("lastname")
  3. public String name;
  4. public LocalDate birth;
  5. public Status status;
  6. public static Person findByNameWithPanacheQLQuery(String name){
  7. return find("name", name).firstResult();
  8. }
  9. public static Person findByNameWithNativeQuery(String name){
  10. return find("{'lastname': ?1}", name).firstResult();
  11. }
  12. }

Both findByNameWithPanacheQLQuery() and findByNameWithNativeQuery() methods will return the same result but query written in PanacheQL will use the entity field name: name, and native query will use the MongoDB field name: lastname.

Query projection

Query projection can be done with the project(Class) method on the PanacheQuery object that is returned by the find() methods.

You can use it to restrict which fields will be returned by the database, the ID field will always be returned, but it’s not mandatory to include it inside the projection class.

For this, you need to create a class (a POJO) that will only contain the projected fields. This POJO needs to be annotated with @ProjectionFor(Entity.class) where Entity is the name of your entity class. The field names, or getters, of the projection class will be used to restrict which properties will be loaded from the database.

Projection can be done for both PanacheQL and native queries.

  1. import io.quarkus.mongodb.panache.ProjectionFor;
  2. import org.bson.codecs.pojo.annotations.BsonProperty;
  3. // using public fields
  4. @ProjectionFor(Person.class)
  5. public class PersonName {
  6. public String name;
  7. }
  8. // using getters
  9. @ProjectionFor(Person.class)
  10. public class PersonNameWithGetter {
  11. private String name;
  12. public String getName(){
  13. return name;
  14. }
  15. public void setName(String name){
  16. this.name = name;
  17. }
  18. }
  19. // only 'name' will be loaded from the database
  20. PanacheQuery<PersonName> shortQuery = Person.find("status ", Status.Alive).project(PersonName.class);
  21. PanacheQuery<PersonName> query = Person.find("'status': ?1", Status.Alive).project(PersonNameWithGetter.class);
  22. PanacheQuery<PersonName> nativeQuery = Person.find("{'status': 'ALIVE'}", Status.Alive).project(PersonName.class);
Using @BsonProperty is not needed to define custom column mappings, as the mappings from the entity class will be used.
You can have your projection class extends from another class. In this case, the parent class also needs to have use @ProjectionFor annotation.

Query debugging

As MongoDB with Panache allows writing simplified queries, it is sometimes handy to log the generated native queries for debugging purpose.

This can be achieved by setting to DEBUG the following log category inside your application.properties:

  1. quarkus.log.category."io.quarkus.mongodb.panache.runtime".level=DEBUG

Transactions

MongoDB offers ACID transactions since version 4.0. MongoDB with Panache doesn’t provide support for them.

Custom IDs

IDs are often a touchy subject. In MongoDB, they are usually auto-generated by the database with an ObjectId type. In MongoDB with Panache the ID are defined by a field named id of the org.bson.types.ObjectId type, but if you want ot customize them, once again we have you covered.

You can specify your own ID strategy by extending PanacheMongoEntityBase instead of PanacheMongoEntity. Then you just declare whatever ID you want as a public field by annotating it by @BsonId:

  1. @MongoEntity
  2. public class Person extends PanacheMongoEntityBase {
  3. @BsonId
  4. public Integer myId;
  5. //...
  6. }

If you’re using repositories, then you will want to extend PanacheMongoRepositoryBase instead of PanacheMongoRepository and specify your ID type as an extra type parameter:

  1. @ApplicationScoped
  2. public class PersonRepository implements PanacheMongoRepositoryBase<Person,Integer> {
  3. //...
  4. }

When using ObjectId, MongoDB will automatically provide a value for you, but if you use a custom field type, you need to provide the value by yourself.

ObjectId can be difficult to use if you want to expose its value in your REST service. So we created JSON-B and Jackson providers to serialize/deserialize them as a String which are automatically registered if your project depends on either the RESTEasy JSON-B extension or the RESTEasy Jackson extension.

Working with Kotlin Data classes

Kotlin data classes are a very convenient way of defining data carrier classes, making them a great match to define an entity class.

But this type of class comes with some limitations: all fields needs to be initialized at construction time or be marked as nullable, and the generated constructor needs to have as parameters all the fields of the data class.

MongoDB with Panache uses the PojoCodec, a MongoDB codec which mandates the presence of a parameterless constructor.

Therefore, if you want to use a data class as an entity class, you need a way to make Kotlin generate an empty constructor. To do so, you need to provide default values for all the fields of your classes. The following sentence from the Kotlin documentation explains it:

On the JVM, if the generated class needs to have a parameterless constructor, default values for all properties have to be specified (see Constructors).

If for whatever reason, the aforementioned solution is deemed unacceptable, there are alternatives.

First, you can create a BSON Codec which will be automatically registered by Quarkus and will be used instead of the PojoCodec. See this part of the documentation: Using BSON codec.

Another option is to use the @BsonCreator annotation to tell the PojoCodec to use the Kotlin data class default constructor, in this case all constructor parameters have to be annotated with @BsonProperty: see Supporting pojos without no args constructor.

This will only work when the entity extends PanacheMongoEntityBase and not PanacheMongoEntity, as the ID field also needs to be included in the constructor.

An example of a Person class defined as a Kotlin data class would look like:

  1. data class Person @BsonCreator constructor (
  2. @BsonId var id: ObjectId,
  3. @BsonProperty("name") var name: String,
  4. @BsonProperty("birth") var birth: LocalDate,
  5. @BsonProperty("status") var status: Status
  6. ): PanacheMongoEntityBase()

Here we use var but note that val can also be used.

The @BsonId annotation is used instead of @BsonProperty(“_id”) for brevity’s sake, but use of either is valid.

The last option is to the use the no-arg compiler plugin. This plugin is configured with a list of annotations, and the end result is the generation of no-args constructor for each class annotated with them.

For MongoDB with Panache, you could use the @MongoEntity annotation on your data class for this:

  1. @MongoEntity
  2. data class Person (
  3. var name: String,
  4. var birth: LocalDate,
  5. var status: Status
  6. ): PanacheMongoEntity()

Reactive Entities and Repositories

MongoDB with Panache allows using reactive style implementation for both entities and repositories. For this, you need to use the Reactive variants when defining your entities : ReactivePanacheMongoEntity or ReactivePanacheMongoEntityBase, and when defining your repositories: ReactivePanacheMongoRepository or ReactivePanacheMongoRepositoryBase.

Mutiny

The reactive API of the MongoDB with Panache uses Mutiny reactive types, if you’re not familiar with them, read the Getting Started with Reactive guide first.

The reactive variant of the Person class will be:

  1. public class ReactivePerson extends ReactivePanacheMongoEntity {
  2. public String name;
  3. public LocalDate birth;
  4. public Status status;
  5. // return name as uppercase in the model
  6. public String getName(){
  7. return name.toUpperCase();
  8. }
  9. // store all names in lowercase in the DB
  10. public void setName(String name){
  11. this.name = name.toLowerCase();
  12. }
  13. }

You will have access to the same functionalities of the imperative variant inside the reactive one: bson annotations, custom ID, PanacheQL, …​ But the methods on your entities or repositories will all return reactive types.

See the equivalent methods from the imperative example with the reactive variant:

  1. // creating a person
  2. ReactivePerson person = new ReactivePerson();
  3. person.name = "Loïc";
  4. person.birth = LocalDate.of(1910, Month.FEBRUARY, 1);
  5. person.status = Status.Alive;
  6. // persist it
  7. Uni<Void> cs1 = person.persist();
  8. person.status = Status.Dead;
  9. // Your must call update() in order to send your entity modifications to MongoDB
  10. Uni<Void> cs2 = person.update();
  11. // delete it
  12. Uni<Void> cs3 = person.delete();
  13. // getting a list of all persons
  14. Uni<List<ReactivePerson>> allPersons = ReactivePerson.listAll();
  15. // finding a specific person by ID
  16. Uni<ReactivePerson> personById = ReactivePerson.findById(personId);
  17. // finding a specific person by ID via an Optional
  18. Uni<Optional<ReactivePerson>> optional = ReactivePerson.findByIdOptional(personId);
  19. personById = optional.map(o -> o.orElseThrow(() -> new NotFoundException()));
  20. // finding all living persons
  21. Uni<List<ReactivePerson>> livingPersons = ReactivePerson.list("status", Status.Alive);
  22. // counting all persons
  23. Uni<Long> countAll = ReactivePerson.count();
  24. // counting all living persons
  25. Uni<Long> countAlive = ReactivePerson.count("status", Status.Alive);
  26. // delete all living persons
  27. Uni<Long> deleteCount = ReactivePerson.delete("status", Status.Alive);
  28. // delete all persons
  29. deleteCount = ReactivePerson.deleteAll();
  30. // delete by id
  31. Uni<Boolean> deleted = ReactivePerson.deleteById(personId);
  32. // set the name of all living persons to 'Mortal'
  33. Uni<Long> updated = ReactivePerson.update("name", "Mortal").where("status", Status.Alive);
If you use MongoDB with Panache in conjunction with RESTEasy, you can directly return a reactive type inside your JAX-RS resource endpoint as long as you include the quarkus-resteasy-mutiny extension.

The same query facility exists for the reactive types, but the stream() methods act differently: they return a Multi (which implement a reactive stream Publisher) instead of a Stream.

It allows more advanced reactive use cases, for example, you can use it to send server-sent events (SSE) via RESTEasy:

  1. import org.jboss.resteasy.annotations.SseElementType;
  2. import org.reactivestreams.Publisher;
  3. import javax.ws.rs.GET;
  4. import javax.ws.rs.Path;
  5. import javax.ws.rs.Produces;
  6. @GET
  7. @Path("/stream")
  8. @Produces(MediaType.SERVER_SENT_EVENTS)
  9. @SseElementType(MediaType.APPLICATION_JSON)
  10. public Multi<ReactivePerson> streamPersons() {
  11. return ReactivePerson.streamAll();
  12. }
@SseElementType(MediaType.APPLICATION_JSON) tells RESTEasy to serialize the object in JSON.

Mocking

Using the active-record pattern

If you are using the active-record pattern you cannot use Mockito directly as it does not support mocking static methods, but you can use the quarkus-panache-mock module which allows you to use Mockito to mock all provided static methods, including your own.

Add this dependency to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-panache-mock</artifactId>
  4. <scope>test</scope>
  5. </dependency>

Given this simple entity:

  1. public class Person extends PanacheMongoEntity {
  2. public String name;
  3. public static List<Person> findOrdered() {
  4. return findAll(Sort.by("lastname", "firstname")).list();
  5. }
  6. }

You can write your mocking test like this:

  1. @QuarkusTest
  2. public class PanacheFunctionalityTest {
  3. @Test
  4. public void testPanacheMocking() {
  5. PanacheMock.mock(Person.class);
  6. // Mocked classes always return a default value
  7. Assertions.assertEquals(0, Person.count());
  8. // Now let's specify the return value
  9. Mockito.when(Person.count()).thenReturn(23l);
  10. Assertions.assertEquals(23, Person.count());
  11. // Now let's change the return value
  12. Mockito.when(Person.count()).thenReturn(42l);
  13. Assertions.assertEquals(42, Person.count());
  14. // Now let's call the original method
  15. Mockito.when(Person.count()).thenCallRealMethod();
  16. Assertions.assertEquals(0, Person.count());
  17. // Check that we called it 4 times
  18. PanacheMock.verify(Person.class, Mockito.times(4)).count();(1)
  19. // Mock only with specific parameters
  20. Person p = new Person();
  21. Mockito.when(Person.findById(12l)).thenReturn(p);
  22. Assertions.assertSame(p, Person.findById(12l));
  23. Assertions.assertNull(Person.findById(42l));
  24. // Mock throwing
  25. Mockito.when(Person.findById(12l)).thenThrow(new WebApplicationException());
  26. Assertions.assertThrows(WebApplicationException.class, () -> Person.findById(12l));
  27. // We can even mock your custom methods
  28. Mockito.when(Person.findOrdered()).thenReturn(Collections.emptyList());
  29. Assertions.assertTrue(Person.findOrdered().isEmpty());
  30. PanacheMock.verify(Person.class).findOrdered();
  31. PanacheMock.verify(Person.class, Mockito.atLeastOnce()).findById(Mockito.any());
  32. PanacheMock.verifyNoMoreInteractions(Person.class);
  33. }
  34. }
1Be sure to call your verify methods on PanacheMock rather than Mockito, otherwise you won’t know what mock object to pass.

Using the repository pattern

If you are using the repository pattern you can use Mockito directly, using the quarkus-junit5-mockito module, which makes mocking beans much easier:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-junit5-mockito</artifactId>
  4. <scope>test</scope>
  5. </dependency>

Given this simple entity:

  1. public class Person {
  2. @BsonId
  3. public Long id;
  4. public String name;
  5. }

And this repository:

  1. @ApplicationScoped
  2. public class PersonRepository implements PanacheMongoRepository<Person> {
  3. public List<Person> findOrdered() {
  4. return findAll(Sort.by("lastname", "firstname")).list();
  5. }
  6. }

You can write your mocking test like this:

  1. @QuarkusTest
  2. public class PanacheFunctionalityTest {
  3. @InjectMock
  4. PersonRepository personRepository;
  5. @Test
  6. public void testPanacheRepositoryMocking() throws Throwable {
  7. // Mocked classes always return a default value
  8. Assertions.assertEquals(0, personRepository.count());
  9. // Now let's specify the return value
  10. Mockito.when(personRepository.count()).thenReturn(23l);
  11. Assertions.assertEquals(23, personRepository.count());
  12. // Now let's change the return value
  13. Mockito.when(personRepository.count()).thenReturn(42l);
  14. Assertions.assertEquals(42, personRepository.count());
  15. // Now let's call the original method
  16. Mockito.when(personRepository.count()).thenCallRealMethod();
  17. Assertions.assertEquals(0, personRepository.count());
  18. // Check that we called it 4 times
  19. Mockito.verify(personRepository, Mockito.times(4)).count();
  20. // Mock only with specific parameters
  21. Person p = new Person();
  22. Mockito.when(personRepository.findById(12l)).thenReturn(p);
  23. Assertions.assertSame(p, personRepository.findById(12l));
  24. Assertions.assertNull(personRepository.findById(42l));
  25. // Mock throwing
  26. Mockito.when(personRepository.findById(12l)).thenThrow(new WebApplicationException());
  27. Assertions.assertThrows(WebApplicationException.class, () -> personRepository.findById(12l));
  28. Mockito.when(personRepository.findOrdered()).thenReturn(Collections.emptyList());
  29. Assertions.assertTrue(personRepository.findOrdered().isEmpty());
  30. // We can even mock your custom methods
  31. Mockito.verify(personRepository).findOrdered();
  32. Mockito.verify(personRepository, Mockito.atLeastOnce()).findById(Mockito.any());
  33. Mockito.verifyNoMoreInteractions(personRepository);
  34. }
  35. }

How and why we simplify MongoDB API

When it comes to writing MongoDB entities, there are a number of annoying things that users have grown used to reluctantly deal with, such as:

  • Duplicating ID logic: most entities need an ID, most people don’t care how it’s set, because it’s not really relevant to your model.

  • Dumb getters and setters: since Java lacks support for properties in the language, we have to create fields, then generate getters and setters for those fields, even if they don’t actually do anything more than read/write the fields.

  • Traditional EE patterns advise to split entity definition (the model) from the operations you can do on them (DAOs, Repositories), but really that requires an unnatural split between the state and its operations even though we would never do something like that for regular objects in the Object Oriented architecture, where state and methods are in the same class. Moreover, this requires two classes per entity, and requires injection of the DAO or Repository where you need to do entity operations, which breaks your edit flow and requires you to get out of the code you’re writing to set up an injection point before coming back to use it.

  • MongoDB queries are super powerful, but overly verbose for common operations, requiring you to write queries even when you don’t need all the parts.

  • MongoDB queries are JSON based, so you will need some String manipulation or using the Document type and it will need a lot of boilerplate code.

With Panache, we took an opinionated approach to tackle all these problems:

  • Make your entities extend PanacheMongoEntity: it has an ID field that is auto-generated. If you require a custom ID strategy, you can extend PanacheMongoEntityBase instead and handle the ID yourself.

  • Use public fields. Get rid of dumb getter and setters. Under the hood, we will generate all getters and setters that are missing, and rewrite every access to these fields to use the accessor methods. This way you can still write useful accessors when you need them, which will be used even though your entity users still use field accesses.

  • With the active record pattern: put all your entity logic in static methods in your entity class and don’t create DAOs. Your entity superclass comes with lots of super useful static methods, and you can add your own in your entity class. Users can just start using your entity Person by typing Person. and getting completion for all the operations in a single place.

  • Don’t write parts of the query that you don’t need: write Person.find("order by name") or Person.find("name = ?1 and status = ?2", "Loïc", Status.Alive) or even better Person.find("name", "Loïc").

That’s all there is to it: with Panache, MongoDB has never looked so trim and neat.

Defining entities in external projects or jars

MongoDB with Panache relies on compile-time bytecode enhancements to your entities.

It attempts to identity archives with Panache entities (and consumers of Panache entities) by the presence of the marker file META-INF/panache-archive.marker. Panache includes an annotation processor that will automatically create this file in archives that depend on Panache (even indirectly). If you have disabled annotation processors you may need to create this file manually in some cases.