-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathhibernate-orm.adoc
1465 lines (1124 loc) · 60.9 KB
/
hibernate-orm.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
////
= Using Hibernate ORM and Jakarta Persistence
include::_attributes.adoc[]
:categories: data
:summary: Hibernate ORM is the de facto Jakarta Persistence implementation and offers you the full breath of an Object Relational Mapper. It works beautifully in Quarkus.
:config-file: application.properties
:topics: data,hibernate-orm,sql,jdbc
:extensions: io.quarkus:quarkus-hibernate-orm
Hibernate ORM is the de facto standard Jakarta Persistence (formerly known as JPA) implementation and offers you the full breadth of an Object Relational Mapper.
It works beautifully in Quarkus.
== 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 `hibernate-orm-quickstart` link:{quickstarts-tree-url}/hibernate-orm-quickstart[directory].
== Setting up and configuring Hibernate ORM
When using Hibernate ORM in Quarkus, you don't need to have a `persistence.xml` resource to configure it.
Using such a classic configuration file is an option, but unnecessary unless you have specific advanced needs;
so we'll see first how Hibernate ORM can be configured without a `persistence.xml` resource.
In Quarkus, you only need to:
* add your configuration settings in `{config-file}`
* annotate your entities with `@Entity` and any other mapping annotation as usual
Other configuration needs have been automated: Quarkus will make some opinionated choices and educated guesses.
Add the following dependencies to your project:
* the Hibernate ORM extension: `io.quarkus:quarkus-hibernate-orm`
* your JDBC driver extension; the following options are available:
- `quarkus-jdbc-db2` for link:https://www.ibm.com/products/db2-database[IBM DB2]
- `quarkus-jdbc-derby` for link:https://db.apache.org/derby/[Apache Derby]
- `quarkus-jdbc-h2` for link:https://www.h2database.com/html/main.html[H2]
- `quarkus-jdbc-mariadb` for link:https://mariadb.com/[MariaDB]
- `quarkus-jdbc-mssql` for link:https://www.microsoft.com/en-gb/sql-server/[Microsoft SQL Server]
- `quarkus-jdbc-mysql` for link:https://www.mysql.com/[MySQL]
- `quarkus-jdbc-oracle` for link:https://www.oracle.com/database/[Oracle Database]
- `quarkus-jdbc-postgresql` for link:https://www.postgresql.org/[PostgreSQL]
For instance:
[source,xml,role="primary asciidoc-tabs-target-sync-cli asciidoc-tabs-target-sync-maven"]
.pom.xml
----
<!-- Hibernate ORM specific dependencies -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<!-- JDBC driver dependencies -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
----
[source,gradle,role="secondary asciidoc-tabs-target-sync-gradle"]
.build.gradle
----
// Hibernate ORM specific dependencies
implementation("io.quarkus:quarkus-hibernate-orm")
// JDBC driver dependencies
implementation("io.quarkus:quarkus-jdbc-postgresql")
----
Annotate your persistent objects with `@Entity`,
then add the relevant configuration properties in `{config-file}`.
[source,properties]
.Example `{config-file}`
----
quarkus.datasource.db-kind = postgresql <1>
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:5432/hibernate_db
quarkus.hibernate-orm.database.generation=drop-and-create <2>
----
<1> xref:datasource.adoc[Configure the datasource].
<2> Drop and create the database at startup (use `update` to only update the schema).
Note that these configuration properties are not the same ones as in your typical Hibernate ORM configuration file.
They will often map to Hibernate ORM configuration properties but could have different names and don't necessarily map 1:1 to each other.
Also, Quarkus will set many Hibernate ORM configuration settings automatically, and will often use more modern defaults.
For a list of the items that you can set in `{config-file}`, see <<hibernate-configuration-properties,Hibernate ORM configuration properties>>.
An `EntityManagerFactory` will be created based on the Quarkus `datasource` configuration as long as the Hibernate ORM extension is listed among your project dependencies.
The dialect will be selected and configured automatically based on your datasource;
you may want to <<hibernate-dialect,configure it to more precisely match your database>>.
You can then happily inject your `EntityManager`:
[source,java]
.Example application bean using Hibernate
----
@ApplicationScoped
public class SantaClausService {
@Inject
EntityManager em; <1>
@Transactional <2>
public void createGift(String giftDescription) {
Gift gift = new Gift();
gift.setName(giftDescription);
em.persist(gift);
}
}
----
<1> Inject your entity manager and have fun
<2> Mark your CDI bean method as `@Transactional` and the `EntityManager` will enlist and flush at commit.
[source,java]
.Example Entity
----
@Entity
public class Gift {
private Long id;
private String name;
@Id
@SequenceGenerator(name = "giftSeq", sequenceName = "gift_id_seq", allocationSize = 1, initialValue = 1)
@GeneratedValue(generator = "giftSeq")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
----
To load SQL statements when Hibernate ORM starts, add an `import.sql` file to the root of your `resources` directory.
This script can contain any SQL DML statements.
Make sure to terminate each statement with a semicolon.
This is useful to have a data set ready for your tests or demos.
WARNING: Make sure to wrap methods modifying your database (e.g. `entity.persist()`) within a transaction. Marking a
CDI bean method `@Transactional` will do that for you and make that method a transaction boundary. We recommend doing
so at your application entry point boundaries like your REST endpoint controllers.
[[hibernate-dialect]]
=== Dialect
[[hibernate-dialect-supported-databases]]
==== Supported databases
For xref:datasource.adoc#extensions-and-database-drivers-reference[supported databases],
the link:{hibernate-orm-docs-url}#database-dialect[Hibernate ORM dialect]
does not need to be set explicitly:
it is selected automatically based on the datasource.
By default, the dialect is configured to target the minimum supported version of the database.
In order for Hibernate ORM to generate more efficient SQL,
to avoid workarounds and to take advantage of more database features,
you can set the database version explicitly:
[source,properties]
.`{config-file}` with an explicit `db-version`
----
quarkus.datasource.db-kind = postgresql
quarkus.datasource.db-version = 14.0 <1>
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:5432/hibernate_db
----
<1> Set the database version. The Hibernate ORM dialect will target that version.
As a rule, the version set here should be as high as possible,
but must be lower than or equal to the version of any database your application will connect to.
[NOTE]
====
As described above, the version can either be preconfigured explicitly via a `quarkus.datasource.db-version` configuration property,
or implicitly set by the Quarkus build process to a minimum supported version of the database.
Quarkus will try to check this preconfigured version against the actual database version on startup,
leading to a startup failure when the actual version is lower.
This is because Hibernate ORM may generate SQL that is invalid
for versions of the database older than what is configured,
which would lead to runtime exceptions.
If the database cannot be reached, a warning will be logged but startup will proceed.
====
[[hibernate-dialect-other-databases]]
==== Other databases
If xref:datasource.adoc#other-databases[your database does not have a corresponding Quarkus extension],
or if the defaults do not match your needs for some reason,
you will need to set the link:{hibernate-orm-docs-url}#database-dialect[Hibernate ORM dialect] explicitly:
[source,properties]
.`{config-file}` with an explicit `dialect`
----
quarkus.datasource.db-kind = postgresql
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:26257/hibernate_db
quarkus.hibernate-orm.dialect=Cockroach <1>
----
<1> Set the Hibernate ORM dialect.
+
For built-in dialects, the expected value is one of the names
in the link:{hibernate-orm-dialect-docs-url}[official list of dialects], *without* the `Dialect` suffix,
for example `Cockroach` for `CockroachDialect`.
+
For third-party dialects, the expected value is the fully-qualified class name,
for example `com.acme.hibernate.AcmeDbDialect`.
[WARNING]
====
In that case, keep in mind that the JDBC driver or Hibernate ORM dialect
may not work properly in GraalVM native executables.
====
As with <<hibernate-dialect-supported-databases,supported databases>>,
you can configure the DB version explicitly to get the most out of Hibernate ORM:
[source,properties]
.`{config-file}` with an explicit `dialect` and `db-version`
----
quarkus.datasource.db-kind = postgresql
quarkus.datasource.db-version = 22.2 <1>
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:26257/hibernate_db
quarkus.hibernate-orm.dialect=Cockroach <2>
----
<1> Set the database version. The Hibernate ORM dialect will target that version.
Since we're targeting CockroachDB here, we're passing the CockroachDB version, not the PostgreSQL version.
<2> Set the Hibernate ORM dialect.
[[hibernate-dialect-varying-database]]
==== Varying database
When enabling <<database-approach,database multi-tenancy>>,
Hibernate ORM will use multiple datasources at runtime for the same persistence unit,
and by default Quarkus cannot tell which datasource is going to be used,
so it will not be able to detect a dialect to use in Hibernate ORM.
For that reason, when enabling <<database-approach,database multi-tenancy>>,
it is recommended to explicitly point the Hibernate ORM configuration to one datasource
among those that will be used at runtime, e.g. with `quarkus.hibernate-orm.datasource=base`
(`base` being the name of a datasource).
When doing so, Quarkus will infer the database version and (if possible) dialect from that datasource.
For unsupported databases, you may still need to set the Hibernate ORM dialect explicitly,
as explained in <<hibernate-dialect-other-databases,this section>>.
[[hibernate-configuration-properties]]
=== Hibernate ORM configuration properties
There are various optional properties useful to refine your `EntityManagerFactory` or guide guesses of Quarkus.
There are no required properties, as long as a default datasource is configured.
When no property is set, Quarkus can typically infer everything it needs to set up Hibernate ORM
and will have it use the default datasource.
The configuration properties listed here allow you to override such defaults, and customize and tune various aspects.
include::{generated-dir}/config/quarkus-hibernate-orm.adoc[opts=optional, leveloffset=+2]
[NOTE]
====
Do not mix <<persistence-xml,`persistence.xml`>> and `quarkus.hibernate-orm.*` properties in `{config-file}`.
Quarkus will raise an exception.
Make up your mind on which approach you want to use.
If your classpath contains a `persistence.xml` that you want to ignore,
set the following configuration property:
[source,properties]
----
quarkus.hibernate-orm.persistence-xml.ignore=true
----
====
[TIP]
====
Want to start a PostgreSQL server on the side with Docker?
[source,bash]
----
docker run --rm=true --name postgres-quarkus-hibernate -e POSTGRES_USER=hibernate \
-e POSTGRES_PASSWORD=hibernate -e POSTGRES_DB=hibernate_db \
-p 5432:5432 postgres:14.1
----
This will start a non-durable empty database: ideal for a quick experiment!
====
[[multiple-persistence-units]]
=== Multiple persistence units
==== Setting up multiple persistence units
It is possible to define multiple persistence units using the Quarkus configuration properties.
The properties at the root of the `quarkus.hibernate-orm.` namespace define the default persistence unit.
For instance, the following snippet defines a default datasource and a default persistence unit:
[source,properties]
----
quarkus.datasource.db-kind=h2
quarkus.datasource.jdbc.url=jdbc:h2:mem:default;DB_CLOSE_DELAY=-1
quarkus.hibernate-orm.database.generation=drop-and-create
----
Using a map based approach, it is possible to define named persistence units:
[source,properties]
----
quarkus.datasource."users".db-kind=h2 <1>
quarkus.datasource."users".jdbc.url=jdbc:h2:mem:users;DB_CLOSE_DELAY=-1
quarkus.datasource."inventory".db-kind=h2 <2>
quarkus.datasource."inventory".jdbc.url=jdbc:h2:mem:inventory;DB_CLOSE_DELAY=-1
quarkus.hibernate-orm."users".database.generation=drop-and-create <3>
quarkus.hibernate-orm."users".datasource=users <4>
quarkus.hibernate-orm."users".packages=org.acme.model.user <5>
quarkus.hibernate-orm."inventory".database.generation=drop-and-create <6>
quarkus.hibernate-orm."inventory".datasource=inventory
quarkus.hibernate-orm."inventory".packages=org.acme.model.inventory
----
<1> Define a datasource named `users`.
<2> Define a datasource named `inventory`.
<3> Define a persistence unit called `users`.
<4> Define the datasource used by the persistence unit.
<5> This configuration property is important, but we will discuss it a bit later.
<6> Define a persistence unit called `inventory` pointing to the `inventory` datasource.
[NOTE]
====
You can mix the default datasource and named datasources or only have one or the other.
====
[NOTE]
====
The default persistence unit points to the default datasource by default.
For named persistence units, the `datasource` property is mandatory.
You can point your persistence unit to the default datasource by setting it to `<default>`
(which is the internal name of the default datasource).
It is perfectly valid to have several persistence units pointing to the same datasource.
====
[[multiple-persistence-units-attaching-model-classes]]
==== Attaching model classes to persistence units
There are two ways to attach model classes to persistence units, and they should not be mixed:
* Via the `packages` configuration property;
* Via the `@io.quarkus.hibernate.orm.PersistenceUnit` package-level annotation.
If both are mixed, the annotations are ignored and only the `packages` configuration properties are taken into account.
Using the `packages` configuration property is simple:
[source,properties]
----
quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.hibernate-orm.packages=org.acme.model.defaultpu
quarkus.hibernate-orm."users".database.generation=drop-and-create
quarkus.hibernate-orm."users".datasource=users
quarkus.hibernate-orm."users".packages=org.acme.model.user
----
This configuration snippet will create two persistence units:
* The default one which will contain all the model classes under the `org.acme.model.defaultpu` package, subpackages included.
* A named `users` persistence unit which will contain all the model classes under the `org.acme.model.user` package, subpackages included.
You can attach several packages to a persistence unit:
[source,properties]
----
quarkus.hibernate-orm."users".packages=org.acme.model.shared,org.acme.model.user
----
All the model classes under the `org.acme.model.shared` and `org.acme.model.user` packages will be attached to the `users` persistence unit.
It is also supported to attach a given model class to several persistence units.
[NOTE]
====
Model classes need to be consistently added to a given persistence unit.
That meant that all dependent model classes of a given entity (mapped super classes, embeddables...) are required to be attached to the persistence unit.
As we are dealing with the persistence unit at the package level, it should be simple enough.
====
[WARNING]
====
Panache entities can be attached to only one persistence unit.
For entities attached to several persistence units, you cannot use Panache.
You can mix the two approaches though and mix Panache entities and traditional entities where multiple persistence units are required.
If you have a use case for that and clever ideas about how to implement it without cluttering the simplified Panache approach,
contact us on the link:{quarkus-mailing-list-index}[quarkus-dev mailing list].
====
The second approach to attach model classes to a persistence unit is to use package-level `@io.quarkus.hibernate.orm.PersistenceUnit` annotations.
Again, the two approaches cannot be mixed.
To obtain a configuration similar to the one above with the `packages` configuration property, create a `package-info.java` file with the following content:
[source,java]
----
@PersistenceUnit("users") <1>
package org.acme.model.user;
import io.quarkus.hibernate.orm.PersistenceUnit;
----
<1> Be careful, use the `@io.quarkus.hibernate.orm.PersistenceUnit` annotation, not the Jakarta Persistence one.
[CAUTION]
====
We only support defining the `@PersistenceUnit` for model classes at the package level,
using the `@PersistenceUnit` annotation at the class level is not supported in this case.
====
Note that, similarly to what we do with the configuration property, we take into account the annotated package but also all its subpackages.
==== CDI integration
If you are familiar with using Hibernate ORM in Quarkus, you probably already have injected the `EntityManager` using CDI:
[source,java]
----
@Inject
EntityManager entityManager;
----
This will inject the `EntityManager` of the default persistence unit.
Injecting the `EntityManager` of a named persistence unit (`users` in our example) is as simple as:
[source,java]
----
@Inject
@PersistenceUnit("users") <1>
EntityManager entityManager;
----
<1> Here again, we use the same `@io.quarkus.hibernate.orm.PersistenceUnit` annotation.
You can inject the `EntityManagerFactory` of a named persistence unit using the exact same mechanism:
[source,java]
----
@Inject
@PersistenceUnit("users")
EntityManagerFactory entityManagerFactory;
----
[[persistence-unit-active]]
=== Activate/deactivate persistence units
If a persistence unit is configured at build time,
by default it is active at runtime,
that is Quarkus will start the corresponding Hibernate ORM `SessionFactory` on application startup.
To deactivate a persistence unit at runtime, set `quarkus.hibernate-orm[.optional name].active` to `false`.
Then Quarkus will not start the corresponding Hibernate ORM `SessionFactory` on application startup.
Any attempt to use the corresponding persistence unit at runtime will fail with a clear error message.
This is in particular useful when you want an application to be able
to xref:datasource.adoc#datasource-active[use one of a pre-determined set of datasources at runtime].
For example, with the following configuration:
[source,properties]
----
quarkus.hibernate-orm."pg".packages=org.acme.model.shared
quarkus.hibernate-orm."pg".datasource=pg
quarkus.hibernate-orm."pg".database.generation=drop-and-create
quarkus.hibernate-orm."pg".active=false
quarkus.datasource."pg".db-kind=h2
quarkus.datasource."pg".active=false
quarkus.datasource."pg".jdbc.url=jdbc:postgresql:///your_database
quarkus.hibernate-orm."oracle".packages=org.acme.model.shared
quarkus.hibernate-orm."oracle".datasource=oracle
quarkus.hibernate-orm."oracle".database.generation=drop-and-create
quarkus.hibernate-orm."oracle".active=false
quarkus.datasource."oracle".db-kind=oracle
quarkus.datasource."oracle".active=false
quarkus.datasource."oracle".jdbc.url=jdbc:oracle:///your_database
----
xref:config-reference.adoc#configuration-sources[Setting] `quarkus.hibernate-orm."pg".active=true` and `quarkus.datasource."pg".active=true` at runtime
will make only the PostgreSQL persistence unit and datasource available,
and setting `quarkus.hibernate-orm."oracle".active=true` and `quarkus.datasource."oracle".active=true` at runtime
will make only the Oracle persistence unit and datasource available.
[TIP]
====
xref:config-reference.adoc#custom-profiles[Custom configuration profiles] can help simplify such a setup.
By appending the following profile-specific configuration to the one above,
you can select a persistence unit/datasource at runtime simply by
xref:config-reference.adoc#multiple-profiles[setting `quarkus.profile`]:
`quarkus.profile=prod,pg` or `quarkus.profile=prod,oracle`.
[source,properties]
----
%pg.quarkus.hibernate-orm."pg".active=true
%pg.quarkus.datasource."pg".active=true
# Add any pg-related runtime configuration here, prefixed with "%pg."
%oracle.quarkus.hibernate-orm."oracle".active=true
%oracle.quarkus.datasource."oracle".active=true
# Add any pg-related runtime configuration here, prefixed with "%pg."
----
====
[TIP]
====
It can also be useful to define a xref:cdi.adoc#ok-you-said-that-there-are-several-kinds-of-beans[CDI bean producer] redirecting to the currently active persistence unit,
like this:
[source,java,indent=0]
----
public class MyProducer {
@Inject
DataSourceSupport dataSourceSupport;
@Inject
@PersistenceUnit("pg")
Session pgSessionBean;
@Inject
@PersistenceUnit("oracle")
Session oracleSessionBean;
@Produces
@ApplicationScoped
public Session session() {
if (dataSourceSupport.getInactiveNames().contains("pg")) {
return oracleSessionBean;
} else {
return pgSessionBean;
}
}
}
----
====
[[persistence-xml]]
== Setting up and configuring Hibernate ORM with a `persistence.xml`
To set up and configure Hibernate ORM, <<hibernate-configuration-properties,using `application.properties`>> is recommended,
but you can alternatively use a `META-INF/persistence.xml` file.
This is mainly useful for migrating existing code to Quarkus.
[WARNING]
====
Using a `persistence.xml` file implies a few constraints:
* Persistence units defined in `persistence.xml` always use the xref:datasource.adoc#configure-a-single-datasource[default datasource].
* Persistence units defined in `persistence.xml` must be configured explicitly:
Quarkus will keep injection of environment-related configuration to a minimum.
+
In particular, Quarkus will not configure the dialect or database version automatically based on the datasource,
so if the default configuration of Hibernate ORM doesn't suit your needs,
you will need to include in `persistence.xml` configuration such as
link:{hibernate-orm-docs-url}#settings-hibernate.dialect[`hibernate.dialect`]/link:{hibernate-orm-docs-url}#settings-jakarta.persistence.database-product-name[`jakarta.persistence.database-product-name`]
and possibly link:{hibernate-orm-docs-url}#settings-jakarta.persistence.database-product-version[`jakarta.persistence.database-product-version`].
* Using `persistence.xml` is incompatible with using `quarkus.hibernate-orm.*` properties in `{config-file}`:
if you mix them, Quarkus will raise an exception.
* Developer experience may be impacted negatively when using `persistence.xml`
compared to when <<hibernate-configuration-properties,using `application.properties`>>,
due to unavailable features, limited guidance in the Quarkus documentation,
and error messages providing resolution hints that cannot be applied (e.g. using `quarkus.hibernate-orm.*` properties).
If your classpath contains a `persistence.xml` that you want to ignore,
set the following configuration property:
[source,properties]
----
quarkus.hibernate-orm.persistence-xml.ignore=true
----
====
Your `pom.xml` dependencies as well as your Java code would be identical to the precedent example. The only
difference is that you would specify your Hibernate ORM configuration in `META-INF/persistence.xml`:
[source,xml]
.Example persistence.xml resource
----
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="CustomerPU" transaction-type="JTA">
<description>My customer entities</description>
<properties>
<!-- Connection specific -->
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<!--
Optimistically create the tables;
will cause background errors being logged if they already exist,
but is practical to retain existing data across runs (or create as needed) -->
<property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="jakarta.persistence.validation.mode" value="NONE"/>
</properties>
</persistence-unit>
</persistence>
----
When using the `persistence.xml` configuration you are configuring Hibernate ORM directly,
so in this case the appropriate reference is the link:{hibernate-orm-docs-url}#configurations[documentation on hibernate.org].
Please remember these are not the same property names as the ones used in the Quarkus `{config-file}`, nor will
the same defaults be applied.
[[xml-mapping]]
== XML mapping
Hibernate ORM in Quarkus supports XML mapping.
You can add mapping files following
the https://jakarta.ee/specifications/persistence/3.0/jakarta-persistence-spec-3.0.html#a16944[`orm.xml` format (Jakarta Persistence)]
or the http://hibernate.org/dtd/hibernate-mapping-3.0.dtd[`hbm.xml` format (specific to Hibernate ORM, deprecated)]:
* in `application.properties` through the (build-time) link:#quarkus-hibernate-orm_quarkus-hibernate-orm-mapping-files[`quarkus.hibernate-orm.mapping-files`] property.
* in <<persistence-xml,`persistence.xml`>> through the `<mapping-file>` element.
XML mapping files are parsed at build time.
[IMPORTANT]
====
The file `META-INF/orm.xml` will always be included by default, if it exists in the classpath.
If that is not what you want, use `quarkus.hibernate-orm.mapping-files = no-file` or `<mapping-file>no-file</mapping-file>`.
====
== Defining entities in external projects or jars
Hibernate ORM in Quarkus relies on compile-time bytecode enhancements to your entities. If you define your entities in the
same project where you build your Quarkus application, everything will work fine.
If the entities come from external projects
or jars, you can make sure that your jar is treated like a Quarkus application library by adding an empty `META-INF/beans.xml` file.
This will allow Quarkus to index and enhance your entities as if they were inside the current project.
[[dev-mode]]
== Hibernate ORM in development mode
Quarkus development mode is really useful for applications that mix front end or services and database access.
There are a few common approaches to make the best of it.
The first choice is to use `quarkus.hibernate-orm.database.generation=drop-and-create` in conjunction with `import.sql`.
That way for every change to your app and in particular to your entities, the database schema will be properly recreated
and your data fixture (stored in `import.sql`) will be used to repopulate it from scratch.
This is best to perfectly control your environment and works magic with Quarkus live reload mode:
your entity changes or any change to your `import.sql` is immediately picked up and the schema updated without restarting the application!
[TIP]
====
By default, in `dev` and `test` modes, Hibernate ORM, upon boot, will read and execute the SQL statements in the `/import.sql` file (if present).
You can change the file name by changing the property `quarkus.hibernate-orm.sql-load-script` in `application.properties`.
====
The second approach is to use `quarkus.hibernate-orm.database.generation=update`.
This approach is best when you do many entity changes but
still need to work on a copy of the production data
or if you want to reproduce a bug that is based on specific database entries.
`update` is a best effort from Hibernate ORM and will fail in specific situations
including altering your database structure which could lead to data loss.
For example if you change structures which violate a foreign key constraint, Hibernate ORM might have to bail out.
But for development, these limitations are acceptable.
The third approach is to use `quarkus.hibernate-orm.database.generation=none`.
This approach is best when you are working on a copy of the production data but want to fully control the schema evolution.
Or if you use a database schema migration tool like xref:flyway.adoc[Flyway] or xref:liquibase.adoc[Liquibase].
With this approach when making changes to an entity, make sure to adapt the database schema accordingly;
you could also use `validate` to have Hibernate verify the schema matches its expectations.
WARNING: Do not use `quarkus.hibernate-orm.database.generation` `drop-and-create` and `update` in your production environment.
These approaches become really powerful when combined with Quarkus configuration profiles.
You can define different xref:config-reference.adoc#profiles[configuration profiles]
to select different behaviors depending on your environment.
This is great because you can define different combinations of Hibernate ORM properties matching the development style you currently need.
[source,properties]
.application.properties
----
%dev.quarkus.hibernate-orm.database.generation = drop-and-create
%dev.quarkus.hibernate-orm.sql-load-script = import-dev.sql
%dev-with-data.quarkus.hibernate-orm.database.generation = update
%dev-with-data.quarkus.hibernate-orm.sql-load-script = no-file
%prod.quarkus.hibernate-orm.database.generation = none
%prod.quarkus.hibernate-orm.sql-load-script = no-file
----
You can start dev mode using a custom profile:
:dev-additional-parameters: -Dquarkus.profile=dev-with-data
include::{includes}/devtools/dev.adoc[]
:!dev-additional-parameters:
== Hibernate ORM in production mode
Quarkus comes with default profiles (`dev`, `test` and `prod`).
And you can add your own custom profiles to describe various environments (`staging`, `prod-us`, etc).
The Hibernate ORM Quarkus extension sets some default configurations differently in dev and test modes than in other environments.
* `quarkus.hibernate-orm.sql-load-script` is set to `no-file` for all profiles except the `dev` and `test` ones.
You can override it in your `application.properties` explicitly
(e.g. `%prod.quarkus.hibernate-orm.sql-load-script = import.sql`)
but we wanted you to avoid overriding your database by accident in prod :)
Speaking of, make sure to not drop your database schema in production!
Add the following in your properties file.
[source,properties]
.application.properties
----
%prod.quarkus.hibernate-orm.database.generation = none
%prod.quarkus.hibernate-orm.sql-load-script = no-file
----
[[flyway]]
== Automatically transitioning to Flyway to Manage Schemas
If you have the xref:flyway.adoc[Flyway extension] installed when running in development mode,
Quarkus provides a simple way to initialize your Flyway configuration
using the schema generated automatically by Hibernate ORM.
This is intended to ease the move from
the early development phase, where Hibernate can be used to quickly set up the schema, to the production phase, where
Flyway is used to manage schema changes.
To use this feature simply open the Dev UI when the `quarkus-flyway` extension is installed and click in the `Datasources`
link in the Flyway pane. Hit the `Create Initial Migration` button and the following will happen:
- A `db/migration/V1.0.0__\{appname\}.sql` file will be created, containing the SQL Hibernate is running to generate the schema
- `quarkus.flyway.baseline-on-migrate` will be set, telling Flyway to automatically create its baseline tables
- `quarkus.flyway.migrate-at-start` will be set, telling Flyway to automatically apply migrations on application startup
- `%dev.quarkus.flyway.clean-at-start` and `%test.quarkus.flyway.clean-at-start` will be set, to clean the DB after reload in dev/test mode
WARNING: This button is simply a convenience to quickly get you started with Flyway, it is up to you to determine how you want to
manage your database schemas in production. In particular the `migrate-at-start` setting may not be right for all environments.
[[caching]]
== Caching
Applications that frequently read the same entities can see their performance improved when the Hibernate ORM second-level cache is enabled.
=== Caching of entities
To enable second-level cache, mark the entities that you want cached with `@jakarta.persistence.Cacheable`:
[source,java]
----
@Entity
@Cacheable
public class Country {
int dialInCode;
// ...
}
----
When an entity is annotated with `@Cacheable`, all its field values are cached except for collections and relations to other entities.
This means the entity can be loaded without querying the database, but be careful as it implies the loaded entity might not reflect recent changes in the database.
=== Caching of collections and relations
Collections and relations need to be individually annotated to be cached; in this case the Hibernate specific `@org.hibernate.annotations.Cache` should be used, which requires also to specify the `CacheConcurrencyStrategy`:
[source,java]
----
package org.acme;
@Entity
@Cacheable
public class Country {
// ...
@OneToMany
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
List<City> cities;
// ...
}
----
=== Caching of queries
Queries can also benefit from second-level caching. Cached query results can be returned immediately to the caller, avoiding to run the query on the database.
Be careful as this implies the results might not reflect recent changes.
To cache a query, mark it as cacheable on the `Query` instance:
[source,java]
----
Query query = ...
query.setHint("org.hibernate.cacheable", Boolean.TRUE);
----
If you have a `NamedQuery` then you can enable caching directly on its definition, which will usually be on an entity:
[source,java]
----
@Entity
@NamedQuery(name = "Fruits.findAll",
query = "SELECT f FROM Fruit f ORDER BY f.name",
hints = @QueryHint(name = "org.hibernate.cacheable", value = "true") )
public class Fruit {
...
----
That's all! Caching technology is already integrated and enabled by default in Quarkus, so it's enough to set which ones are safe to be cached.
=== Tuning of Cache Regions
Caches store the data in separate regions to isolate different portions of data; such regions are assigned a name, which is useful for configuring each region independently, or to monitor their statistics.
By default, entities are cached in regions named after their fully qualified name, e.g. `org.acme.Country`.
Collections are cached in regions named after the fully qualified name of their owner entity and collection field name, separated by `#` character, e.g. `org.acme.Country#cities`.
All cached queries are by default kept in a single region dedicated to them called `default-query-results-region`.
All regions are bounded by size and time by default. The defaults are `10000` max entries, and `100` seconds as maximum idle time.
The size of each region can be customized via the `quarkus.hibernate-orm.cache."<region_name>".memory.object-count` property (Replace _<region_name>_ with the actual region name).
To set the maximum idle time, provide the duration (see note on duration's format below) via the `quarkus.hibernate-orm.cache."<region_name>".expiration.max-idle` property (Replace _<region_name>_ with the actual region name).
[NOTE]
====
The double quotes are mandatory if your region name contains a dot. For instance:
[source,properties]
----
quarkus.hibernate-orm.cache."org.acme.MyEntity".memory.object-count=1000
----
====
include::{includes}/duration-format-note.adoc[]
=== Limitations of Caching
The caching technology provided within Quarkus is currently quite rudimentary and limited.
The team thought it was better to have _some_ caching capability to start with, than having nothing; you can expect better caching solution to be integrated in future releases, and any help and feedback in this area is very welcome.
[NOTE]
====
These caches are kept locally, so they are not invalidated or updated when changes are made to the persistent store by other applications.
Also, when running multiple copies of the same application (in a cluster, for example on Kubernetes/OpenShift), caches in separate copies of the application aren't synchronized.
For these reasons, enabling caching is only suitable when certain assumptions can be made: we strongly recommend that only entities, collections and queries which never change are cached. Or at most, that when indeed such an entity is mutated and allowed to be read out of date (stale) this has no impact on the expectations of the application.
Following this advice guarantees applications get the best performance out of the second-level cache and yet avoid unexpected behaviour.
On top of immutable data, in certain contexts it might be acceptable to enable caching also on mutable data; this could be a necessary tradeoff on selected
entities which are read frequently and for which some degree of staleness is acceptable; this " acceptable degree of staleness" can be tuned by setting eviction properties.
This is however not recommended and should be done with extreme care, as it might
produce unexpected and unforeseen effects on the data.
Rather than enabling caching on mutable data, ideally a better solution would be to use a clustered cache; however at this time Quarkus doesn't provide any such implementation: feel free to get in touch and let this need known so that the team can take this into account.
====
Finally, the second-level cache can be disabled globally by setting `hibernate.cache.use_second_level_cache` to `false`; this is a setting that needs to be specified in the `persistence.xml` configuration file.
When second-level cache is disabled, all cache annotations are ignored and all queries are run ignoring caches; this is generally useful only to diagnose issues.
[[envers]]
== Hibernate Envers
The Envers extension to Hibernate ORM aims to provide an easy auditing / versioning solution for entity classes.
In Quarkus, Envers has a dedicated Quarkus Extension `io.quarkus:quarkus-hibernate-envers`; you just need to add this to your project to start using it.
[source,xml]
.Additional dependency to enable Hibernate Envers
----
<!-- Add the Hibernate Envers extension -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-envers</artifactId>
</dependency>
----
At this point the extension does not expose additional configuration properties.
For more information about Hibernate Envers, see link:https://hibernate.org/orm/envers/[hibernate.org/orm/envers/].
[[metrics]]
== Metrics
Either xref:telemetry-micrometer.adoc[Micrometer] or xref:smallrye-metrics.adoc[SmallRye Metrics] are
capable of exposing metrics that Hibernate ORM collects at runtime. To enable exposure of Hibernate metrics
on the `/q/metrics` endpoint, make sure your project depends on a metrics extension and set the configuration property `quarkus.hibernate-orm.metrics.enabled` to `true`.
When using xref:smallrye-metrics.adoc[SmallRye Metrics], metrics will be available under the `vendor` scope.
== Limitations and other things you should know
Quarkus does not modify the libraries it uses; this rule applies to Hibernate ORM as well: when using
this extension you will mostly have the same experience as using the original library.
But while they share the same code, Quarkus does configure some components automatically and injects custom implementations
for some extension points; this should be transparent and useful but if you're an expert of Hibernate you might want to
know what is being done.
=== Automatic build time enhancement
Hibernate ORM can use build time enhanced entities; normally this is not mandatory, but it's useful and will have your
applications perform better.
Typically, you would need to adapt your build scripts to include the Hibernate Enhancement plugins; in Quarkus this is
not necessary as the enhancement step is integrated in the build and analysis of the Quarkus application.
[WARNING]
====
Due to the usage of enhancement, using the `clone()` method on entities is currently not supported
as it will also clone some enhancement-specific fields that are specific to the entity.
This limitation might be removed in the future.
====
=== Automatic integration
Transaction Manager integration::
You don't need to set this up, Quarkus automatically injects the reference to the Narayana Transaction Manager.
The dependency is included automatically as a transitive dependency of the Hibernate ORM extension.
All configuration is optional; for more details see xref:transaction.adoc[Using Transactions in Quarkus].
Connection pool::
Don't need to choose one either. Quarkus automatically includes the Agroal connection pool;
configure your datasource as in the above examples and it will set up Hibernate ORM to use Agroal.
More details about this connection pool can be found in xref:datasource.adoc[Quarkus - Datasources].
Second Level Cache::
As explained earlier in the <<caching,Caching section>>, you don't need to pick an implementation.
A suitable implementation based on technologies from link:https://infinispan.org/[Infinispan] and link:https://github.com/ben-manes/caffeine[Caffeine] is included as a transitive dependency of the Hibernate ORM extension, and automatically integrated during the build.
=== Limitations
XML mapping with duplicate files in the classpath::
<<xml-mapping,XML mapping>> files are expected to have a unique path.
+
In practice, it's only possible to have duplicate XML mapping files in the classpath in very specific scenarios.