-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
mongodb-panache.adoc
1476 lines (1103 loc) · 53.5 KB
/
mongodb-panache.adoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////
This guide is maintained in the main Quarkus repository
and pull requests should be submitted there:
https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc
////
= Simplified MongoDB with Panache
include::_attributes.adoc[]
:categories: data
:summary: This guide covers the usage of MongoDB using active records and repositories.
:config-file: application.properties
:mongodb-doc-root-url: https://www.mongodb.com/docs/drivers/java/sync/current
:topics: data,mongodb,nosql,panache,kotlin
:extensions: io.quarkus:quarkus-mongodb-panache,io.quarkus:quarkus-mongodb-client
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 link:{mongodb-doc-root-url}/fundamentals/data-formats/documents/#document[`Document`].
MongoDB with Panache provides active record style entities (and repositories) like you have in xref:hibernate-orm-panache.adoc[Hibernate ORM with Panache] and focuses on making your entities trivial and fun to write in Quarkus.
It is built on top of the xref:mongodb.adoc[MongoDB Client] extension.
== First: an example
Panache allows you to write your MongoDB entities like this:
[source,java]
----
public class Person extends PanacheMongoEntity {
public String name;
public LocalDate birth;
public Status status;
public static Person findByName(String name){
return find("name", name).firstResult();
}
public static List<Person> findAlive(){
return list("status", Status.Alive);
}
public static void deleteLoics(){
delete("name", "Loïc");
}
}
----
You have noticed how much more compact and readable the code is compared to using the MongoDB API?
Does this look interesting? Read on!
NOTE: 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.
NOTE: what was described above is essentially the link:https://www.martinfowler.com/eaaCatalog/activeRecord.html[active record pattern], sometimes just called the entity pattern.
MongoDB with Panache also allows for the use of the more classical link:https://martinfowler.com/eaaCatalog/repository.html[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 {quickstarts-clone-url}`, or download an {quickstarts-archive-url}[archive].
The solution is located in the `mongodb-panache-quickstart` link:{quickstarts-tree-url}/mongodb-panache-quickstart[directory].
== Creating the Maven project
First, we need a new project. Create a new project with the following command:
:create-app-artifact-id: mongodb-panache-quickstart
:create-app-extensions: resteasy-reactive-jackson,mongodb-panache
include::{includes}/devtools/create-app.adoc[]
This command generates a Maven structure importing the RESTEasy Reactive Jackson and MongoDB with Panache extensions.
After this, the `quarkus-mongodb-panache` extension has been added to your build file.
If you don't want to generate a new project, add the dependency in your build file:
[source,xml,role="primary asciidoc-tabs-target-sync-cli asciidoc-tabs-target-sync-maven"]
.pom.xml
----
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-mongodb-panache</artifactId>
</dependency>
----
[source,gradle,role="secondary asciidoc-tabs-target-sync-gradle"]
.build.gradle
----
implementation("io.quarkus:quarkus-mongodb-panache")
----
[NOTE]
====
If your project is already configured to use other annotation processors, you will need to additionally add the Panache annotation processor:
[source,xml,role="primary asciidoc-tabs-target-sync-cli asciidoc-tabs-target-sync-maven"]
.pom.xml
----
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<parameters>${maven.compiler.parameters}</parameters>
<annotationProcessorPaths>
<!-- Your existing annotation processor(s)... -->
<path>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-panache-common</artifactId>
<version>${quarkus.platform.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
----
[source,gradle,role="secondary asciidoc-tabs-target-sync-gradle"]
.build.gradle
----
annotationProcessor("io.quarkus:quarkus-panache-common")
----
====
== Setting up and configuring MongoDB with Panache
To get started:
* add your settings in `{config-file}`
* 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 `{config-file}`.
[source,properties]
----
# configure the MongoDB client for a replica set of two nodes
quarkus.mongodb.connection-string = mongodb://mongo1:27017,mongo2:27017
# mandatory if you don't specify the name of the database using @MongoEntity
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 multitenant application, see xref:mongodb.adoc#multiple-mongodb-clients[Multiple MongoDB Clients]. Otherwise, the default client will be used.
* the name of the database, otherwise the `quarkus.mongodb.database` property or a link:{mongodb-doc-root-url}#multitenancy[`MongoDatabaseResolver`] implementation 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 xref:mongodb.adoc#configuring-the-mongodb-database[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.
[source,java]
----
@MongoEntity(collection="ThePerson")
public class Person extends PanacheMongoEntity {
public String name;
// will be persisted as a 'birth' field in MongoDB
@BsonProperty("birth")
public LocalDate birthDate;
public Status status;
}
----
NOTE: 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 link:{mongodb-doc-root-url}/fundamentals/data-formats/document-data-format-pojo[PojoCodecProvider] to convert 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,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:
[source,java]
----
public class Person extends PanacheMongoEntity {
public String name;
public LocalDate birth;
public Status status;
// return name as uppercase in the model
public String getName(){
return name.toUpperCase();
}
// store all names in lowercase in the DB
public void setName(String name){
this.name = name.toLowerCase();
}
}
----
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:
[source,java]
----
// creating a person
Person person = new Person();
person.name = "Loïc";
person.birth = LocalDate.of(1910, Month.FEBRUARY, 1);
person.status = Status.Alive;
// persist it: if you keep the default ObjectId ID field, it will be populated by the MongoDB driver
person.persist();
person.status = Status.Dead;
// Your must call update() in order to send your entity modifications to MongoDB
person.update();
// delete it
person.delete();
// getting a list of all Person entities
List<Person> allPersons = Person.listAll();
// finding a specific person by ID
// here we build a new ObjectId, but you can also retrieve it from the existing entity after being persisted
ObjectId personId = new ObjectId(idAsString);
person = Person.findById(personId);
// finding a specific person by ID via an Optional
Optional<Person> optional = Person.findByIdOptional(personId);
person = optional.orElseThrow(() -> new NotFoundException());
// finding all living persons
List<Person> livingPersons = Person.list("status", Status.Alive);
// counting all persons
long countAll = Person.count();
// counting all living persons
long countAlive = Person.count("status", Status.Alive);
// delete all living persons
Person.delete("status", Status.Alive);
// delete all persons
Person.deleteAll();
// delete by id
boolean deleted = Person.deleteById(personId);
// set the name of all living persons to 'Mortal'
long updated = Person.update("name", "Mortal").where("status", Status.Alive);
----
All `list` methods have equivalent `stream` versions.
[source,java]
----
Stream<Person> persons = Person.streamAll();
List<String> namesButEmmanuels = persons
.map(p -> p.name.toLowerCase() )
.filter( n -> ! "emmanuel".equals(n) )
.collect(Collectors.toList());
----
NOTE: 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.
[source,java]
----
public class Person extends PanacheMongoEntity {
public String name;
public LocalDate birth;
public Status status;
public static Person findByName(String name){
return find("name", name).firstResult();
}
public static List<Person> findAlive(){
return list("status", Status.Alive);
}
public static void deleteLoics(){
delete("name", "Loïc");
}
}
----
== 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.
[source,java]
----
@MongoEntity(collection="ThePerson")
public class Person {
public ObjectId id; // used by MongoDB for the _id field
public String name;
public LocalDate birth;
public Status status;
}
----
NOTE: 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 link:{mongodb-doc-root-url}/fundamentals/data-formats/document-data-format-pojo/[PojoCodecProvider] to convert 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,Custom IDs>>.
- `@BsonProperty`: customize the serialized name of the field.
- `@BsonIgnore`: ignore a field during the serialization.
TIP: 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 with the active record pattern, injected in your Repository,
by making them implements `PanacheMongoRepository`:
[source,java]
----
@ApplicationScoped
public class PersonRepository implements PanacheMongoRepository<Person> {
// put your custom logic here as instance methods
public Person findByName(String name){
return find("name", name).firstResult();
}
public List<Person> findAlive(){
return list("status", Status.Alive);
}
public void deleteLoics(){
delete("name", "Loïc");
}
}
----
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:
[source,java]
----
@Inject
PersonRepository personRepository;
@GET
public long count(){
return personRepository.count();
}
----
=== Most useful operations
Once you have written your repository, here are the most common operations you will be able to perform:
[source,java]
----
// creating a person
Person person = new Person();
person.name = "Loïc";
person.birth = LocalDate.of(1910, Month.FEBRUARY, 1);
person.status = Status.Alive;
// persist it: if you keep the default ObjectId ID field, it will be populated by the MongoDB driver
personRepository.persist(person);
person.status = Status.Dead;
// Your must call update() in order to send your entity modifications to MongoDB
personRepository.update(person);
// delete it
personRepository.delete(person);
// getting a list of all Person entities
List<Person> allPersons = personRepository.listAll();
// finding a specific person by ID
// here we build a new ObjectId, but you can also retrieve it from the existing entity after being persisted
ObjectId personId = new ObjectId(idAsString);
person = personRepository.findById(personId);
// finding a specific person by ID via an Optional
Optional<Person> optional = personRepository.findByIdOptional(personId);
person = optional.orElseThrow(() -> new NotFoundException());
// finding all living persons
List<Person> livingPersons = personRepository.list("status", Status.Alive);
// counting all persons
long countAll = personRepository.count();
// counting all living persons
long countAlive = personRepository.count("status", Status.Alive);
// delete all living persons
personRepository.delete("status", Status.Alive);
// delete all persons
personRepository.deleteAll();
// delete by id
boolean deleted = personRepository.deleteById(personId);
// set the name of all living persons to 'Mortal'
long updated = personRepository.update("name", "Mortal").where("status", Status.Alive);
----
All `list` methods have equivalent `stream` versions.
[source,java]
----
Stream<Person> persons = personRepository.streamAll();
List<String> namesButEmmanuels = persons
.map(p -> p.name.toLowerCase() )
.filter( n -> ! "emmanuel".equals(n) )
.collect(Collectors.toList());
----
NOTE: 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.
NOTE: 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.
== Writing a Jakarta REST resource
First, include one of the RESTEasy extensions to enable Jakarta REST endpoints, for example, add the `io.quarkus:quarkus-resteasy-reactive-jackson` dependency for Jakarta REST and JSON support.
Then, you can create the following resource to create/read/update/delete your Person entity:
[source,java]
----
@Path("/persons")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
@GET
public List<Person> list() {
return Person.listAll();
}
@GET
@Path("/{id}")
public Person get(String id) {
return Person.findById(new ObjectId(id));
}
@POST
public Response create(Person person) {
person.persist();
return Response.created(URI.create("/persons/" + person.id)).build();
}
@PUT
@Path("/{id}")
public void update(String id, Person person) {
person.update();
}
@DELETE
@Path("/{id}")
public void delete(String id) {
Person person = Person.findById(new ObjectId(id));
if(person == null) {
throw new NotFoundException();
}
person.delete();
}
@GET
@Path("/search/{name}")
public Person search(String name) {
return Person.findByName(name);
}
@GET
@Path("/count")
public Long count() {
return Person.count();
}
}
----
== 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:
[source,java]
----
// create a query for all living persons
PanacheQuery<Person> livingPersons = Person.find("status", Status.Alive);
// make it use pages of 25 entries at a time
livingPersons.page(Page.ofSize(25));
// get the first page
List<Person> firstPage = livingPersons.list();
// get the second page
List<Person> secondPage = livingPersons.nextPage().list();
// get page 7
List<Person> page7 = livingPersons.page(Page.of(7, 25)).list();
// get the number of pages
int numberOfPages = livingPersons.pageCount();
// get the total number of entities returned by this query without paging
int count = livingPersons.count();
// and you can chain methods of course
return Person.find("status", Status.Alive)
.page(Page.ofSize(25))
.nextPage()
.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.
[source,java]
----
// create a query for all living persons
PanacheQuery<Person> livingPersons = Person.find("status", Status.Alive);
// make it use a range: start at index 0 until index 24 (inclusive).
livingPersons.range(0, 24);
// get the range
List<Person> firstRange = livingPersons.list();
// to get the next range, you need to call range again
List<Person> secondRange = livingPersons.range(25, 49).list();
----
[WARNING]
====
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:
[source,java]
----
List<Person> persons = Person.list(Sort.by("name").and("birth"));
// and with more restrictions
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 link:https://docs.oracle.com/javaee/7/tutorial/persistence-querylanguage.htm#BNBTG[JPQL] (or link:{hibernate-orm-docs-url}#hql[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 link:https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex[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]}}`
WARNING: MongoDB queries must be valid JSON documents,
using the same field multiple times in a query is not allowed using PanacheQL as it would generate an invalid JSON
(see link:https://github.com/quarkusio/quarkus/issues/12086[this issue on GitHub]).
We also handle some basic date type transformations: all fields of type `Date`, `LocalDate`, `LocalDateTime` or `Instant` will be mapped to the
link:https://docs.mongodb.com/manual/reference/bson-types/#date[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/update methods.
MongoDB with Panache offers operations to update multiple documents based on an update document and a query :
`Person.update("foo = ?1 and 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 and status = ?2` will be mapped to the update document `{'$set' : {'firstname': ?1, 'status': ?2}}`
- `firstname = :firstname and status = :status` will be mapped to the update document `{'$set' : {'firstname': :firstname, 'status': :status}}`
- `{'firstname' : ?1 and 'status' : ?2}` will be mapped to the update document `{'$set' : {'firstname': ?1, 'status': ?2}}`
- `{'firstname' : :firstname and 'status' : :status}` will be mapped to the update document `{'$set' : {'firstname': :firstname, 'status': :status}}`
- `{'$inc': {'cpt': ?1}}` will be used as-is
=== Query parameters
You can pass query parameters, for both native and PanacheQL queries, by index (1-based) as shown below:
[source,java]
----
Person.find("name = ?1 and status = ?2", "Loïc", Status.Alive);
Person.find("{'name': ?1, 'status': ?2}", "Loïc", Status.Alive);
----
Or by name using a `Map`:
[source,java]
----
Map<String, Object> params = new HashMap<>();
params.put("name", "Loïc");
params.put("status", Status.Alive);
Person.find("name = :name and status = :status", params);
Person.find("{'name': :name, 'status', :status}", params);
----
Or using the convenience class `Parameters` either as is or to build a `Map`:
[source,java]
----
// generate a Map
Person.find("name = :name and status = :status",
Parameters.with("name", "Loïc").and("status", Status.Alive).map());
// use it as-is
Person.find("{'name': :name, 'status': :status}",
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:
[source,java]
----
public class Person extends PanacheMongoEntity {
@BsonProperty("lastname")
public String name;
public LocalDate birth;
public Status status;
public static Person findByNameWithPanacheQLQuery(String name){
return find("name", name).firstResult();
}
public static Person findByNameWithNativeQuery(String name){
return find("{'lastname': ?1}", name).firstResult();
}
}
----
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.
[source,java]
----
import io.quarkus.mongodb.panache.common.ProjectionFor;
import org.bson.codecs.pojo.annotations.BsonProperty;
// using public fields
@ProjectionFor(Person.class)
public class PersonName {
public String name;
}
// using getters
@ProjectionFor(Person.class)
public class PersonNameWithGetter {
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
// only 'name' will be loaded from the database
PanacheQuery<PersonName> shortQuery = Person.find("status ", Status.Alive).project(PersonName.class);
PanacheQuery<PersonName> query = Person.find("'status': ?1", Status.Alive).project(PersonNameWithGetter.class);
PanacheQuery<PersonName> nativeQuery = Person.find("{'status': 'ALIVE'}", Status.Alive).project(PersonName.class);
----
TIP: Using `@BsonProperty` is not needed to define custom column mappings, as the mappings from the entity class will be used.
TIP: You can have your projection class extends from another class. In this case, the parent class also needs to have use `@ProjectionFor` annotation.
TIP: If you run Java 17+, records are a good fit for projection classes.
== 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`:
[source,properties]
----
quarkus.log.category."io.quarkus.mongodb.panache.common.runtime".level=DEBUG
----
== The PojoCodecProvider: easy object to BSON document conversion.
MongoDB with Panache uses the link:{mongodb-doc-root-url}/fundamentals/data-formats/document-data-format-pojo/[PojoCodecProvider], with link:{mongodb-doc-root-url}/fundamentals/data-formats/document-data-format-pojo/#configure-the-driver-for-pojos[automatic POJO support],
to automatically convert your object to a BSON document.
In case you encounter the `org.bson.codecs.configuration.CodecConfigurationException` exception, it means the codec is not able to
automatically convert your object.
This codec obeys the Java Bean standard, so it will successfully convert a POJO using public fields or getters/setters.
You can use `@BsonIgnore` to make a field, or a getter/setter, ignored by the codec.
If your class doesn't obey these rules (for example by including a method that starts with `get` but is not a setter),
you could provide a custom codec for it.
Your custom codec will be automatically discovered and registered inside the codec registry.
See xref:mongodb.adoc#simplifying-mongodb-client-usage-using-bson-codec[Using BSON codec].
== Transactions
MongoDB offers ACID transactions since version 4.0.
To use them with MongoDB with Panache you need to annotate the method that starts the transaction with the `@Transactional` annotation.
In MongoDB, a transaction is only possible on a replicaset,
luckily our xref:mongodb.adoc#dev-services[Dev Services for MongoDB] setups a single node replicaset so it is compatible with transactions.
== 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 to 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`:
[source,java]
----
@MongoEntity
public class Person extends PanacheMongoEntityBase {
@BsonId
public Integer myId;
//...
}
----
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:
[source,java]
----
@ApplicationScoped
public class PersonRepository implements PanacheMongoRepositoryBase<Person,Integer> {
//...
}
----
[NOTE]
====
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 Jackson and JSON-B providers to serialize/deserialize them as a `String` which are automatically registered if your project depends on either the RESTEasy Reactive Jackson extension or the RESTEasy Reactive JSON-B extension.
[IMPORTANT]
====
If you use the standard `ObjectId` ID type, don't forget to retrieve your entity by creating a new `ObjectId` when the identifier comes from a path parameter. For example:
[source,java]
----
@GET
@Path("/{id}")
public Person findById(String id) {
return Person.findById(new ObjectId(id));
}
----
====
== 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 link:{mongodb-doc-root-url}/fundamentals/data-formats/document-data-format-pojo[PojoCodecProvider], 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 `PojoCodecProvider`.
See this part of the documentation: xref:mongodb.adoc#simplifying-mongodb-client-usage-using-bson-codec[Using BSON codec].
Another option is to use the `@BsonCreator` annotation to tell the `PojoCodecProvider` to use the Kotlin data class default constructor,
in this case all constructor parameters have to be annotated with `@BsonProperty`: see link:{mongodb-doc-root-url}/fundamentals/data-formats/pojo-customization/#pojos-without-no-argument-constructors[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:
[source,kotlin]
----
data class Person @BsonCreator constructor (
@BsonId var id: ObjectId,
@BsonProperty("name") var name: String,
@BsonProperty("birth") var birth: LocalDate,
@BsonProperty("status") var status: Status
): PanacheMongoEntityBase()
----
[TIP]
====
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 link:https://kotlinlang.org/docs/reference/compiler-plugins.html#no-arg-compiler-plugin[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:
[source,kotlin]
----
@MongoEntity
data class Person (
var name: String,
var birth: LocalDate,
var status: Status
): PanacheMongoEntity()
----
[[reactive]]
== 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`.
[TIP]
.Mutiny
====
The reactive API of MongoDB with Panache uses Mutiny reactive types.
If you are not familiar with Mutiny, check xref:mutiny-primer.adoc[Mutiny - an intuitive reactive programming library].
====
The reactive variant of the `Person` class will be:
[source,java]
----
public class ReactivePerson extends ReactivePanacheMongoEntity {
public String name;
public LocalDate birth;
public Status status;
// return name as uppercase in the model
public String getName(){
return name.toUpperCase();
}
// store all names in lowercase in the DB
public void setName(String name){
this.name = name.toLowerCase();
}
}
----
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:
[source,java]
----
// creating a person
ReactivePerson person = new ReactivePerson();
person.name = "Loïc";
person.birth = LocalDate.of(1910, Month.FEBRUARY, 1);
person.status = Status.Alive;
// persist it: if you keep the default ObjectId ID field, it will be populated by the MongoDB driver,
// and accessible when uni1 will be resolved
Uni<ReactivePerson> uni1 = person.persist();
person.status = Status.Dead;
// Your must call update() in order to send your entity modifications to MongoDB
Uni<ReactivePerson> uni2 = person.update();
// delete it
Uni<Void> uni3 = person.delete();
// getting a list of all persons
Uni<List<ReactivePerson>> allPersons = ReactivePerson.listAll();
// finding a specific person by ID
// here we build a new ObjectId, but you can also retrieve it from the existing entity after being persisted
ObjectId personId = new ObjectId(idAsString);
Uni<ReactivePerson> personById = ReactivePerson.findById(personId);
// finding a specific person by ID via an Optional
Uni<Optional<ReactivePerson>> optional = ReactivePerson.findByIdOptional(personId);
personById = optional.map(o -> o.orElseThrow(() -> new NotFoundException()));
// finding all living persons
Uni<List<ReactivePerson>> livingPersons = ReactivePerson.list("status", Status.Alive);
// counting all persons
Uni<Long> countAll = ReactivePerson.count();
// counting all living persons
Uni<Long> countAlive = ReactivePerson.count("status", Status.Alive);
// delete all living persons
Uni<Long> deleteCount = ReactivePerson.delete("status", Status.Alive);
// delete all persons
deleteCount = ReactivePerson.deleteAll();
// delete by id
Uni<Boolean> deleted = ReactivePerson.deleteById(personId);
// set the name of all living persons to 'Mortal'
Uni<Long> updated = ReactivePerson.update("name", "Mortal").where("status", Status.Alive);
----
TIP: If you use MongoDB with Panache in conjunction with RESTEasy Reactive, you can directly return a reactive type inside your Jakarta REST resource endpoint.
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 Reactive:
[source,java]
----
import org.jboss.resteasy.reactive.RestStreamElementType;
import org.reactivestreams.Publisher;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
@GET
@Path("/stream")
@Produces(MediaType.SERVER_SENT_EVENTS)