3
.gitignore
vendored
3
.gitignore
vendored
@@ -11,4 +11,5 @@ target/
|
||||
node_modules
|
||||
package-lock.json
|
||||
package.json
|
||||
node
|
||||
node
|
||||
build/
|
||||
|
||||
15
README.adoc
15
README.adoc
@@ -1,6 +1,3 @@
|
||||
image:https://spring.io/badges/spring-data-jpa/ga.svg[Spring Data JPA,link=https://projects.spring.io/spring-data-jpa/#quick-start]
|
||||
image:https://spring.io/badges/spring-data-jpa/snapshot.svg[Spring Data JPA,link=https://projects.spring.io/spring-data-jpa/#quick-start]
|
||||
|
||||
= Spring Data JPA image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-jpa%2Fmain&subject=Build[link=https://jenkins.spring.io/view/SpringData/job/spring-data-jpa/] https://gitter.im/spring-projects/spring-data[image:https://badges.gitter.im/spring-projects/spring-data.svg[Gitter]]
|
||||
|
||||
Spring Data JPA, part of the larger https://projects.spring.io/spring-data[Spring Data] family, makes it easy to implement JPA-based repositories.
|
||||
@@ -104,7 +101,7 @@ Add the Maven dependency:
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${version}.RELEASE</version>
|
||||
<version>${version}</version>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
@@ -115,7 +112,7 @@ If you'd rather like the latest snapshots of the upcoming major version, use our
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${version}.BUILD-SNAPSHOT</version>
|
||||
<version>${version}-SNAPSHOT</version>
|
||||
</dependency>
|
||||
|
||||
<repository>
|
||||
@@ -130,7 +127,7 @@ If you'd rather like the latest snapshots of the upcoming major version, use our
|
||||
Having trouble with Spring Data? We’d love to help!
|
||||
|
||||
* Check the
|
||||
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/[reference documentation], and https://docs.spring.io/spring-data/jpa/docs/current/api/[Javadocs].
|
||||
https://docs.spring.io/spring-data/jpa/reference/[reference documentation], and https://docs.spring.io/spring-data/jpa/docs/current/api/[Javadocs].
|
||||
* Learn the Spring basics – Spring Data builds on Spring Framework, check the https://spring.io[spring.io] web-site for a wealth of reference documentation.
|
||||
If you are just starting out with Spring, try one of the https://spring.io/guides[guides].
|
||||
* If you are upgrading, check out the https://github.com/spring-projects/spring-data-jpa/releases[Spring Data JPA release notes] and scroll down to the one you're considering. See the details there. (Also check out the https://github.com/spring-projects/spring-data-jpa/releases/latest[latest stable release])
|
||||
@@ -159,7 +156,7 @@ You also need JDK 17 or above.
|
||||
$ ./mvnw clean install
|
||||
----
|
||||
|
||||
If you want to build with the regular `mvn` command, you will need https://maven.apache.org/run-maven/index.html[Maven v3.5.0 or above].
|
||||
If you want to build with the regular `mvn` command, you will need https://maven.apache.org/run-maven/index.html[Maven v3.8.0 or above].
|
||||
|
||||
_Also see link:CONTRIBUTING.adoc[CONTRIBUTING.adoc] if you wish to submit pull requests, and in particular please sign the https://cla.pivotal.io/sign/spring[Contributor’s Agreement] before your first non-trivial change._
|
||||
|
||||
@@ -169,10 +166,10 @@ Building the documentation builds also the project without running tests.
|
||||
|
||||
[source,bash]
|
||||
----
|
||||
$ ./mvnw clean install -Pdistribute
|
||||
$ ./mvnw clean install -Pantora
|
||||
----
|
||||
|
||||
The generated documentation is available from `target/site/reference/html/index.html`.
|
||||
The generated documentation is available from `target/antora/site/index.html`.
|
||||
|
||||
== Guides
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ antora:
|
||||
root_component_name: 'data-jpa'
|
||||
site:
|
||||
title: Spring Data JPA
|
||||
url: https://docs.spring.io/spring-data-jpa/reference/
|
||||
url: https://docs.spring.io/spring-data/jpa/reference/
|
||||
content:
|
||||
sources:
|
||||
- url: ./../../..
|
||||
|
||||
@@ -1,34 +1,35 @@
|
||||
* xref:index.adoc[Overview]
|
||||
** xref:commons/upgrade.adoc[]
|
||||
* xref:repositories/introduction.adoc[]
|
||||
|
||||
* xref:jpa.adoc[]
|
||||
** xref:jpa/getting-started.adoc[]
|
||||
** xref:repositories/core-concepts.adoc[]
|
||||
** xref:repositories/definition.adoc[]
|
||||
** xref:repositories/create-instances.adoc[]
|
||||
** xref:repositories/query-methods-details.adoc[]
|
||||
** xref:repositories/projections.adoc[]
|
||||
** xref:repositories/custom-implementations.adoc[]
|
||||
** xref:repositories/core-domain-events.adoc[]
|
||||
** xref:repositories/core-extensions.adoc[]
|
||||
** xref:repositories/null-handling.adoc[]
|
||||
** xref:repositories/query-keywords-reference.adoc[]
|
||||
** xref:repositories/query-return-types-reference.adoc[]
|
||||
* xref:jpa.adoc[]
|
||||
** xref:jpa/configuration.adoc[]
|
||||
** xref:jpa/entity-persistence.adoc[]
|
||||
** xref:repositories/query-methods-details.adoc[]
|
||||
** xref:jpa/query-methods.adoc[]
|
||||
** xref:repositories/projections.adoc[]
|
||||
** xref:jpa/stored-procedures.adoc[]
|
||||
** xref:jpa/specifications.adoc[]
|
||||
** xref:query-by-example.adoc[]
|
||||
** xref:repositories/query-by-example.adoc[]
|
||||
** xref:jpa/transactions.adoc[]
|
||||
** xref:jpa/locking.adoc[]
|
||||
** xref:auditing.adoc[]
|
||||
** xref:jpa/misc-context.adoc[]
|
||||
** xref:jpa/misc-merging-persistence-units.adoc[]
|
||||
** xref:jpa/jpd-misc-cdi-integration.adoc[]
|
||||
** xref:repositories/custom-implementations.adoc[]
|
||||
** xref:repositories/core-domain-events.adoc[]
|
||||
** xref:repositories/null-handling.adoc[]
|
||||
** xref:repositories/core-extensions.adoc[]
|
||||
** xref:repositories/query-keywords-reference.adoc[]
|
||||
** xref:repositories/query-return-types-reference.adoc[]
|
||||
** xref:jpa/faq.adoc[]
|
||||
** xref:jpa/glossary.adoc[]
|
||||
|
||||
* xref:envers.adoc[]
|
||||
** xref:envers/introduction.adoc[]
|
||||
** xref:envers/configuration.adoc[]
|
||||
** xref:envers/usage.adoc[]
|
||||
|
||||
* https://github.com/spring-projects/spring-data-commons/wiki[Wiki]
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
= JPA
|
||||
:page-section-summary-toc: 1
|
||||
|
||||
This chapter points out the specialties for repository support for JPA. This builds on the core repository support explained in xref:repositories/introduction.adoc[Working with Spring Data Repositories]. Make sure you have a sound understanding of the basic concepts explained there.
|
||||
This chapter points out the specialties for repository support for JPA. This builds on the core repository support explained in xref:repositories.adoc[Working with Spring Data Repositories]. Make sure you have a sound understanding of the basic concepts explained there.
|
||||
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
[[jpa.configuration]]
|
||||
= Configuration
|
||||
|
||||
This section describes configuring Spring Data JPA through either:
|
||||
|
||||
* "`<<jpa.namespace,Spring Namespace>>`" (XML configuration)
|
||||
* "`<<jpa.java-config,Annotation-based Configuration>>`" (Java configuration)
|
||||
|
||||
[[jpa.java-config]]
|
||||
== Annotation-based Configuration
|
||||
The Spring Data JPA repositories support can be activated through both JavaConfig as well as a custom XML namespace, as shown in the following example:
|
||||
|
||||
.Spring Data JPA repositories using JavaConfig
|
||||
====
|
||||
[source, java]
|
||||
----
|
||||
@Configuration
|
||||
@EnableJpaRepositories
|
||||
@EnableTransactionManagement
|
||||
class ApplicationConfig {
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
|
||||
return builder.setType(EmbeddedDatabaseType.HSQL).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
|
||||
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
vendorAdapter.setGenerateDdl(true);
|
||||
|
||||
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
|
||||
factory.setJpaVendorAdapter(vendorAdapter);
|
||||
factory.setPackagesToScan("com.acme.domain");
|
||||
factory.setDataSource(dataSource());
|
||||
return factory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
|
||||
|
||||
JpaTransactionManager txManager = new JpaTransactionManager();
|
||||
txManager.setEntityManagerFactory(entityManagerFactory);
|
||||
return txManager;
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
NOTE: You must create `LocalContainerEntityManagerFactoryBean` and not `EntityManagerFactory` directly, since the former also participates in exception translation mechanisms in addition to creating `EntityManagerFactory`.
|
||||
|
||||
The preceding configuration class sets up an embedded HSQL database by using the `EmbeddedDatabaseBuilder` API of `spring-jdbc`. Spring Data then sets up an `EntityManagerFactory` and uses Hibernate as the sample persistence provider. The last infrastructure component declared here is the `JpaTransactionManager`. Finally, the example activates Spring Data JPA repositories by using the `@EnableJpaRepositories` annotation, which essentially carries the same attributes as the XML namespace. If no base package is configured, it uses the one in which the configuration class resides.
|
||||
|
||||
[[jpa.namespace]]
|
||||
== Spring Namespace
|
||||
|
||||
The JPA module of Spring Data contains a custom namespace that allows defining repository beans. It also contains certain features and element attributes that are special to JPA. Generally, the JPA repositories can be set up by using the `repositories` element, as shown in the following example:
|
||||
|
||||
.Setting up JPA repositories by using the namespace
|
||||
====
|
||||
[source, xml]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/data/jpa
|
||||
https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
|
||||
|
||||
<jpa:repositories base-package="com.acme.repositories" />
|
||||
|
||||
</beans>
|
||||
----
|
||||
====
|
||||
|
||||
TIP: Which is better, JavaConfig or XML? XML is how Spring was configured long ago. In today's era of fast-growing Java, record types, annotations, and more, new projects typically use as much pure Java as possible. While there is no immediate plan to remove XML support, some of the newest features MAY not be available through XML.
|
||||
|
||||
Using the `repositories` element looks up Spring Data repositories as described in xref:repositories/create-instances.adoc[Creating Repository Instances]. Beyond that, it activates persistence exception translation for all beans annotated with `@Repository`, to let exceptions being thrown by the JPA persistence providers be converted into Spring's `DataAccessException` hierarchy.
|
||||
|
||||
[[jpa.namespace.custom-namespace-attributes]]
|
||||
=== Custom Namespace Attributes
|
||||
Beyond the default attributes of the `repositories` element, the JPA namespace offers additional attributes to let you gain more detailed control over the setup of the repositories:
|
||||
|
||||
.Custom JPA-specific attributes of the `repositories` element
|
||||
[options = "autowidth"]
|
||||
|===============
|
||||
|`entity-manager-factory-ref`|Explicitly wire the `EntityManagerFactory` to be used with the repositories being detected by the `repositories` element. Usually used if multiple `EntityManagerFactory` beans are used within the application. If not configured, Spring Data automatically looks up the `EntityManagerFactory` bean with the name `entityManagerFactory` in the `ApplicationContext`.
|
||||
|`transaction-manager-ref`|Explicitly wire the `PlatformTransactionManager` to be used with the repositories being detected by the `repositories` element. Usually only necessary if multiple transaction managers or `EntityManagerFactory` beans have been configured. Default to a single defined `PlatformTransactionManager` inside the current `ApplicationContext`.
|
||||
|===============
|
||||
|
||||
NOTE: Spring Data JPA requires a `PlatformTransactionManager` bean named `transactionManager` to be present if no explicit `transaction-manager-ref` is defined.
|
||||
|
||||
[[jpa.bootstrap-mode]]
|
||||
== Bootstrap Mode
|
||||
|
||||
By default, Spring Data JPA repositories are default Spring beans.
|
||||
They are singleton scoped and eagerly initialized.
|
||||
During startup, they already interact with the JPA `EntityManager` for verification and metadata analysis purposes.
|
||||
Spring Framework supports the initialization of the JPA `EntityManagerFactory` in a background thread because that process usually takes up a significant amount of startup time in a Spring application.
|
||||
To make use of that background initialization effectively, we need to make sure that JPA repositories are initialized as late as possible.
|
||||
|
||||
As of Spring Data JPA 2.1 you can now configure a `BootstrapMode` (either via the `@EnableJpaRepositories` annotation or the XML namespace) that takes the following values:
|
||||
|
||||
* `DEFAULT` (default) -- Repositories are instantiated eagerly unless explicitly annotated with `@Lazy`.
|
||||
The lazification only has effect if no client bean needs an instance of the repository as that will require the initialization of the repository bean.
|
||||
* `LAZY` -- Implicitly declares all repository beans lazy and also causes lazy initialization proxies to be created to be injected into client beans.
|
||||
That means, that repositories will not get instantiated if the client bean is simply storing the instance in a field and not making use of the repository during initialization.
|
||||
Repository instances will be initialized and verified upon first interaction with the repository.
|
||||
* `DEFERRED` -- Fundamentally the same mode of operation as `LAZY`, but triggering repository initialization in response to an `ContextRefreshedEvent` so that repositories are verified before the application has completely started.
|
||||
|
||||
[[jpa.bootstrap-mode.recommendations]]
|
||||
=== Recommendations
|
||||
|
||||
If you're not using asynchronous JPA bootstrap stick with the default bootstrap mode.
|
||||
|
||||
In case you bootstrap JPA asynchronously, `DEFERRED` is a reasonable default as it will make sure the Spring Data JPA bootstrap only waits for the `EntityManagerFactory` setup if that itself takes longer than initializing all other application components.
|
||||
Still, it makes sure that repositories are properly initialized and validated before the application signals it's up.
|
||||
|
||||
`LAZY` is a decent choice for testing scenarios and local development.
|
||||
Once you are pretty sure that repositories can properly bootstrap, or in cases where you are testing other parts of the application, running verification for all repositories might unnecessarily increase the startup time.
|
||||
The same applies to local development in which you only access parts of the application that might need to have a single repository initialized.
|
||||
|
||||
67
src/main/antora/modules/ROOT/pages/jpa/getting-started.adoc
Normal file
67
src/main/antora/modules/ROOT/pages/jpa/getting-started.adoc
Normal file
@@ -0,0 +1,67 @@
|
||||
[[jpa.getting-started]]
|
||||
= Getting Started
|
||||
|
||||
An easy way to bootstrap setting up a working environment is to create a Spring-based project via https://start.spring.io/#!type=maven-project&dependencies=h2,data-jpa[start.spring.io] or create a Spring project in https://spring.io/tools[Spring Tools].
|
||||
|
||||
[[jpa.examples-repo]]
|
||||
== Examples Repository
|
||||
|
||||
The GitHub https://github.com/spring-projects/spring-data-examples[spring-data-examples repository] hosts several examples that you can download and play around with to get a feel for how the library works.
|
||||
|
||||
[[redis.hello-world]]
|
||||
== Hello World
|
||||
|
||||
Let's start with a simple entity and its corresponding repository:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@Entity
|
||||
class Person {
|
||||
|
||||
@Id @GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
// getters and setters ommited for brevity
|
||||
}
|
||||
|
||||
interface PersonRepository extends Repository<Person, Long> {
|
||||
|
||||
Person save(Person person);
|
||||
|
||||
Optional<Person> findById(long id);
|
||||
}
|
||||
----
|
||||
|
||||
Create the main application to run, as the following example shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
CommandLineRunner runner(PersonRepository repository) {
|
||||
return args -> {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
|
||||
repository.save(person);
|
||||
Person saved = repository.findById(person.getId()).orElseThrow(NoSuchElementException::new);
|
||||
};
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
Even in this simple example, there are a few notable things to point out:
|
||||
|
||||
* Repository instances are automatically implemented.
|
||||
When used as parameters of `@Bean` methods, these will be autowired without further need for annotations.
|
||||
* The basic repository extends `Repository`.
|
||||
We suggest to consider how much API surface you want to expose towards your application.
|
||||
More complex repository interfaces are `ListCrudRepository` or `JpaRepository`.
|
||||
@@ -1,27 +0,0 @@
|
||||
[[jpa.misc.jpa-context]]
|
||||
= Using `JpaContext` in Custom Implementations
|
||||
|
||||
When working with multiple `EntityManager` instances and xref:repositories/custom-implementations.adoc#repositories.custom-implementations[custom repository implementations], you need to wire the correct `EntityManager` into the repository implementation class. You can do so by explicitly naming the `EntityManager` in the `@PersistenceContext` annotation or, if the `EntityManager` is `@Autowired`, by using `@Qualifier`.
|
||||
|
||||
As of Spring Data JPA 1.9, Spring Data JPA includes a class called `JpaContext` that lets you obtain the `EntityManager` by managed domain class, assuming it is managed by only one of the `EntityManager` instances in the application. The following example shows how to use `JpaContext` in a custom repository:
|
||||
|
||||
.Using `JpaContext` in a custom repository implementation
|
||||
====
|
||||
[source, java]
|
||||
----
|
||||
class UserRepositoryImpl implements UserRepositoryCustom {
|
||||
|
||||
private final EntityManager em;
|
||||
|
||||
@Autowired
|
||||
public UserRepositoryImpl(JpaContext context) {
|
||||
this.em = context.getEntityManagerByManagedType(User.class);
|
||||
}
|
||||
|
||||
…
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The advantage of this approach is that, if the domain type gets assigned to a different persistence unit, the repository does not have to be touched to alter the reference to the persistence unit.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[[jpa.query-methods]]
|
||||
= Query Methods
|
||||
= JPA Query Methods
|
||||
|
||||
This section describes the various ways to create a query with Spring Data JPA.
|
||||
|
||||
@@ -357,9 +357,9 @@ This is a lighter variant than paging because it does not require the total resu
|
||||
3. <<repositories.scrolling.keyset,Keyset-baset scrolling>>.
|
||||
This method avoids https://use-the-index-luke.com/no-offset[the shortcomings of offset-based result retrieval by leveraging database indexes].
|
||||
|
||||
Read more on xref:repositories/query-methods-details.adoc#repositories.scrolling.guidance,which method to use best>> for your particular arrangement.
|
||||
Read more on <<repositories.scrolling.guidance,which method to use best>> for your particular arrangement.
|
||||
|
||||
You can use the Scroll API with query methods, xref:query-by-example.adoc[Query-by-Example], and xref:repositories/core-extensions.adoc#core.extensions.querydsl[Querydsl].
|
||||
You can use the Scroll API with query methods, xref:repositories/query-by-example.adoc[Query-by-Example], and xref:repositories/core-extensions.adoc#core.extensions.querydsl[Querydsl].
|
||||
|
||||
NOTE: Scrolling with String-based query methods is not yet supported.
|
||||
Scrolling is also not supported using stored `@Procedure` query methods.
|
||||
@@ -432,7 +432,7 @@ Another use case for the `#{#entityName}` expression in a query string is if you
|
||||
@MappedSuperclass
|
||||
public abstract class AbstractMappedType {
|
||||
…
|
||||
String attribute
|
||||
String attribute;
|
||||
}
|
||||
|
||||
@Entity
|
||||
@@ -507,7 +507,7 @@ But sometimes, your query may simply be too complicated for the techniques offer
|
||||
In that situation, consider:
|
||||
|
||||
* If you haven't already, simply write the query yourself using xref:jpa/query-methods.adoc#jpa.query-methods.at-query[`@Query`].
|
||||
* If that doesn't fit your needs, consider implementing a xref:repositories/custom-implementations.adoc#repositories.custom-implementations[custom implementation]. This lets you register a method in your repository while leaving the implementation completely up to you. This gives you the ability to:
|
||||
* If that doesn't fit your needs, consider implementing a xref:repositories/custom-implementations.adoc[custom implementation]. This lets you register a method in your repository while leaving the implementation completely up to you. This gives you the ability to:
|
||||
** Talk directly to the `EntityManager` (writing pure HQL/JPQL/EQL/native SQL or using the *Criteria API*)
|
||||
** Leverage Spring Framework's `JdbcTemplate` (native SQL)
|
||||
** Use another 3rd-party database toolkit.
|
||||
|
||||
@@ -1 +1,126 @@
|
||||
include::{commons}@data-commons::page$repositories/create-instances.adoc[]
|
||||
[[jpa.configuration]]
|
||||
= Configuration
|
||||
|
||||
This section describes configuring Spring Data JPA through either:
|
||||
|
||||
* "`<<jpa.java-config,Annotation-based Configuration>>`" (Java configuration)
|
||||
* "`<<repositories.create-instances.xml,Spring Namespace>>`" (XML configuration)
|
||||
|
||||
[[jpa.java-config]]
|
||||
== Annotation-based Configuration
|
||||
The Spring Data JPA repositories support can be activated through both JavaConfig as well as a custom XML namespace, as shown in the following example:
|
||||
|
||||
.Spring Data JPA repositories using JavaConfig
|
||||
====
|
||||
[source, java]
|
||||
----
|
||||
@Configuration
|
||||
@EnableJpaRepositories
|
||||
@EnableTransactionManagement
|
||||
class ApplicationConfig {
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
|
||||
return builder.setType(EmbeddedDatabaseType.HSQL).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
|
||||
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
vendorAdapter.setGenerateDdl(true);
|
||||
|
||||
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
|
||||
factory.setJpaVendorAdapter(vendorAdapter);
|
||||
factory.setPackagesToScan("com.acme.domain");
|
||||
factory.setDataSource(dataSource());
|
||||
return factory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
|
||||
|
||||
JpaTransactionManager txManager = new JpaTransactionManager();
|
||||
txManager.setEntityManagerFactory(entityManagerFactory);
|
||||
return txManager;
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
NOTE: You must create `LocalContainerEntityManagerFactoryBean` and not `EntityManagerFactory` directly, since the former also participates in exception translation mechanisms in addition to creating `EntityManagerFactory`.
|
||||
|
||||
The preceding configuration class sets up an embedded HSQL database by using the `EmbeddedDatabaseBuilder` API of `spring-jdbc`. Spring Data then sets up an `EntityManagerFactory` and uses Hibernate as the sample persistence provider. The last infrastructure component declared here is the `JpaTransactionManager`. Finally, the example activates Spring Data JPA repositories by using the `@EnableJpaRepositories` annotation, which essentially carries the same attributes as the XML namespace. If no base package is configured, it uses the one in which the configuration class resides.
|
||||
|
||||
[[repositories.create-instances.xml]]
|
||||
== Spring Namespace
|
||||
|
||||
The JPA module of Spring Data contains a custom namespace that allows defining repository beans. It also contains certain features and element attributes that are special to JPA. Generally, the JPA repositories can be set up by using the `repositories` element, as shown in the following example:
|
||||
|
||||
.Setting up JPA repositories by using the namespace
|
||||
====
|
||||
[source, xml]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/data/jpa
|
||||
https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
|
||||
|
||||
<jpa:repositories base-package="com.acme.repositories" />
|
||||
|
||||
</beans>
|
||||
----
|
||||
====
|
||||
|
||||
TIP: Which is better, JavaConfig or XML? XML is how Spring was configured long ago. In today's era of fast-growing Java, record types, annotations, and more, new projects typically use as much pure Java as possible. While there is no immediate plan to remove XML support, some of the newest features MAY not be available through XML.
|
||||
|
||||
Using the `repositories` element it activates persistence exception translation for all beans annotated with `@Repository`, to let exceptions being thrown by the JPA persistence providers be converted into Spring's `DataAccessException` hierarchy.
|
||||
|
||||
[[jpa.namespace.custom-namespace-attributes]]
|
||||
=== Custom Namespace Attributes
|
||||
Beyond the default attributes of the `repositories` element, the JPA namespace offers additional attributes to let you gain more detailed control over the setup of the repositories:
|
||||
|
||||
.Custom JPA-specific attributes of the `repositories` element
|
||||
[options = "autowidth"]
|
||||
|===============
|
||||
|`entity-manager-factory-ref`|Explicitly wire the `EntityManagerFactory` to be used with the repositories being detected by the `repositories` element. Usually used if multiple `EntityManagerFactory` beans are used within the application. If not configured, Spring Data automatically looks up the `EntityManagerFactory` bean with the name `entityManagerFactory` in the `ApplicationContext`.
|
||||
|`transaction-manager-ref`|Explicitly wire the `PlatformTransactionManager` to be used with the repositories being detected by the `repositories` element. Usually only necessary if multiple transaction managers or `EntityManagerFactory` beans have been configured. Default to a single defined `PlatformTransactionManager` inside the current `ApplicationContext`.
|
||||
|===============
|
||||
|
||||
NOTE: Spring Data JPA requires a `PlatformTransactionManager` bean named `transactionManager` to be present if no explicit `transaction-manager-ref` is defined.
|
||||
|
||||
[[jpa.bootstrap-mode]]
|
||||
== Bootstrap Mode
|
||||
|
||||
By default, Spring Data JPA repositories are default Spring beans.
|
||||
They are singleton scoped and eagerly initialized.
|
||||
During startup, they already interact with the JPA `EntityManager` for verification and metadata analysis purposes.
|
||||
Spring Framework supports the initialization of the JPA `EntityManagerFactory` in a background thread because that process usually takes up a significant amount of startup time in a Spring application.
|
||||
To make use of that background initialization effectively, we need to make sure that JPA repositories are initialized as late as possible.
|
||||
|
||||
As of Spring Data JPA 2.1 you can now configure a `BootstrapMode` (either via the `@EnableJpaRepositories` annotation or the XML namespace) that takes the following values:
|
||||
|
||||
* `DEFAULT` (default) -- Repositories are instantiated eagerly unless explicitly annotated with `@Lazy`.
|
||||
The lazification only has effect if no client bean needs an instance of the repository as that will require the initialization of the repository bean.
|
||||
* `LAZY` -- Implicitly declares all repository beans lazy and also causes lazy initialization proxies to be created to be injected into client beans.
|
||||
That means, that repositories will not get instantiated if the client bean is simply storing the instance in a field and not making use of the repository during initialization.
|
||||
Repository instances will be initialized and verified upon first interaction with the repository.
|
||||
* `DEFERRED` -- Fundamentally the same mode of operation as `LAZY`, but triggering repository initialization in response to an `ContextRefreshedEvent` so that repositories are verified before the application has completely started.
|
||||
|
||||
[[jpa.bootstrap-mode.recommendations]]
|
||||
=== Recommendations
|
||||
|
||||
If you're not using asynchronous JPA bootstrap stick with the default bootstrap mode.
|
||||
|
||||
In case you bootstrap JPA asynchronously, `DEFERRED` is a reasonable default as it will make sure the Spring Data JPA bootstrap only waits for the `EntityManagerFactory` setup if that itself takes longer than initializing all other application components.
|
||||
Still, it makes sure that repositories are properly initialized and validated before the application signals it's up.
|
||||
|
||||
`LAZY` is a decent choice for testing scenarios and local development.
|
||||
Once you are pretty sure that repositories can properly bootstrap, or in cases where you are testing other parts of the application, running verification for all repositories might unnecessarily increase the startup time.
|
||||
The same applies to local development in which you only access parts of the application that might need to have a single repository initialized.
|
||||
|
||||
|
||||
@@ -1 +1,29 @@
|
||||
include::{commons}@data-commons::page$repositories/custom-implementations.adoc[]
|
||||
|
||||
[[jpa.misc.jpa-context]]
|
||||
== Using `JpaContext` in Custom Implementations
|
||||
|
||||
When working with multiple `EntityManager` instances and xref:repositories/custom-implementations.adoc#repositories.custom-implementations[custom repository implementations], you need to wire the correct `EntityManager` into the repository implementation class. You can do so by explicitly naming the `EntityManager` in the `@PersistenceContext` annotation or, if the `EntityManager` is `@Autowired`, by using `@Qualifier`.
|
||||
|
||||
As of Spring Data JPA 1.9, Spring Data JPA includes a class called `JpaContext` that lets you obtain the `EntityManager` by managed domain class, assuming it is managed by only one of the `EntityManager` instances in the application. The following example shows how to use `JpaContext` in a custom repository:
|
||||
|
||||
.Using `JpaContext` in a custom repository implementation
|
||||
====
|
||||
[source, java]
|
||||
----
|
||||
class UserRepositoryImpl implements UserRepositoryCustom {
|
||||
|
||||
private final EntityManager em;
|
||||
|
||||
@Autowired
|
||||
public UserRepositoryImpl(JpaContext context) {
|
||||
this.em = context.getEntityManagerByManagedType(User.class);
|
||||
}
|
||||
|
||||
…
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The advantage of this approach is that, if the domain type gets assigned to a different persistence unit, the repository does not have to be touched to alter the reference to the persistence unit.
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
= Query by Example
|
||||
|
||||
include::{commons}@data-commons::page$query-by-example.adoc[leveloffset=+1]
|
||||
include::{commons}@data-commons::page$query-by-example.adoc[]
|
||||
|
||||
[[query-by-example.running]]
|
||||
In Spring Data JPA, you can use Query by Example with Repositories, as shown in the following example:
|
||||
Reference in New Issue
Block a user