From 83acd5b0501e51e1d2365bd66854a3554c3c3e74 Mon Sep 17 00:00:00 2001 From: Stephane Nicoll Date: Tue, 20 Jun 2023 15:21:12 +0200 Subject: [PATCH] Document JPA configuration best practices with AOT Closes gh-30498 --- .../modules/ROOT/pages/core/aot.adoc | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/framework-docs/modules/ROOT/pages/core/aot.adoc b/framework-docs/modules/ROOT/pages/core/aot.adoc index 106cae3959cb..e3c8c985b2ab 100644 --- a/framework-docs/modules/ROOT/pages/core/aot.adoc +++ b/framework-docs/modules/ROOT/pages/core/aot.adoc @@ -318,6 +318,51 @@ Java:: ---- ====== +[[aot.bestpractices.jpa]] +=== JPA + +The JPA persistence unit has to be known upfront for certain optmizations to apply. Consider the following basic example: + +[tabs] +====== +Java:: ++ +[source,java,indent=0,subs="verbatim,quotes",role="primary"] +---- + @Bean + LocalContainerEntityManagerFactoryBean customDBEntityManagerFactory(DataSource dataSource) { + LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); + factoryBean.setDataSource(dataSource); + factoryBean.setPackagesToScan("com.example.app"); + return factoryBean; + } +---- +====== + +To make sure the scanning occurs ahead of time, a `PersistenceManagedTypes` bean must be declared and used by the +factory bean definition, as shown by the following example: + +[tabs] +====== +Java:: ++ +[source,java,indent=0,subs="verbatim,quotes",role="primary"] +---- + @Bean + PersistenceManagedTypes persistenceManagedTypes(ResourceLoader resourceLoader) { + return new PersistenceManagedTypesScanner(resourceLoader) + .scan("com.example.app"); + } + + @Bean + LocalContainerEntityManagerFactoryBean customDBEntityManagerFactory(DataSource dataSource, PersistenceManagedTypes managedTypes) { + LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); + factoryBean.setDataSource(dataSource); + factoryBean.setManagedTypes(managedTypes); + return factoryBean; + } +---- +====== [[aot.hints]] == Runtime Hints