Download ebooks file Beginning Spring Data: Data Access and Persistence for Spring Framework 6 and Boot 3 Andres Sacco all chapters
Download ebooks file Beginning Spring Data: Data Access and Persistence for Spring Framework 6 and Boot 3 Andres Sacco all chapters
com
https://ebookmass.com/product/beginning-spring-data-data-
access-and-persistence-for-spring-framework-6-and-
boot-3-andres-sacco/
OR CLICK HERE
DOWLOAD NOW
https://ebookmass.com/product/pro-spring-security-securing-spring-
framework-6-and-boot-3-based-java-applications-third-edition-massimo-
nardone/
ebookmass.com
https://ebookmass.com/product/encyclopedia-of-mycology-two-volume-set-
oscar-zaragoza/
ebookmass.com
A God of Death & Rest (Pine Hollow Series Book 2) K. M.
Moronova
https://ebookmass.com/product/a-god-of-death-rest-pine-hollow-series-
book-2-k-m-moronova/
ebookmass.com
https://ebookmass.com/product/repairing-bertrand-russells-1913-theory-
of-knowledge-gregory-landini/
ebookmass.com
https://ebookmass.com/product/the-challenge-of-world-theatre-
history-1st-ed-edition-steve-tillis/
ebookmass.com
https://ebookmass.com/product/social-stratification-class-race-and-
gender-in-sociological-perspective-4th-edition-ebook-pdf/
ebookmass.com
https://ebookmass.com/product/constructing-quantum-mechanics-volume-
one-the-scaffold-1900%e2%80%921923-1st-edition-anthony-duncan/
ebookmass.com
SPEAK (MindTap Course List) 4th Edition, (Ebook PDF)
https://ebookmass.com/product/speak-mindtap-course-list-4th-edition-
ebook-pdf/
ebookmass.com
Andres Sacco
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
% java -version
openjdk 17.0.4 2022-07-19 LTS
OpenJDK Runtime Environment Microsoft-38107 (build
17.0.4+8-LTS)
OpenJDK 64-Bit Server VM Microsoft-38107 (build
17.0.4+8-LTS, mixed mode, sharing)
% mvn --version
Apache Maven 3.8.1
Maven home: /usr/share/maven
Finally, check that Docker runs correctly on your machine. You can
do so by running the following command.
% docker --version
Docker version 20.10.12, build 20.10.12-
0ubuntu2~20.04.1
Source Code
The source code for this book is available for download at
github.com/apress/beginning-spring-data.
How This Book Is Structured
This book is structured into four parts.
The first part (Chapters 1–3) surveys the history of Java persistence
and the patterns connected to persistence, explains how to create a
project in Spring, and briefly explains the different types of
persistence available in Spring Data.
The second part (Chapters 4–6) gives a basic tour of key features of
Spring Data with relational databases and presents tools for
versioning changes in a database.
The third part (Chapters 7–10) briefly explores how Spring Data
interacts with non-relational databases like Cassandra, Redis,
MongoDB, and Neo4j.
The fourth part (Chapters 11–14) covers advanced topics like
performing unit and performance tests using different libraries. The
last chapter describes some best practices for using Spring Data.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit http://www.apress.com/source-code.
Acknowledgments
I would like to thank my family members and friends for their
encouragement and support during the process of writing this book.
My wife, Gisela, was always patient when I spent long hours at my
computer desk working on this book
My little daughter, Francesca, who helped me to relax when I was
writing each chapter
My baby, Allegra, who is the new family member and my inspiration
to write this book
My friends, German Canale and Julian Delley, who always encouraged
me to write a book and supported me when I doubted myself
A special mention to Manuel Jordan for guiding me in improving the
quality of my book
I sincerely thank the team at Apress for their support during the
publication of this book. Thanks to Mark Powers for providing excellent
support. Finally, thanks to Steve Anglin for suggesting and giving me the
possibility to write a book about Spring Data.
Table of Contents
Part I: Introduction
Chapter 1:Application Architecture
Why Persistence Is So Important
The History of Persistence
JDBC
EJB
JPA
Spring Data
Object Mapping
Repository Support
Architectures Types
Layers
Hexagonal
Persistence Design Patterns
Data Access Object (DAO)
Repository Pattern
Data Transfer Object (DTO)
Specification Pattern
Other Patterns
Summary
Chapter 2:Spring Basics and Beyond
Spring Basics
Spring Boot
Basic Application Setup
Creating an API Using Spring Initialzr
Creating an API in the IDE
How to Run the Application
Best Practices
Preventing Conflicts with the Dependencies
Documenting the Endpoints
Logging All the Details
Maintaining and Updating the Dependencies
Summary
Chapter 3:Spring Data and Different Types of Persistence
What Is Spring Data?
How Does Spring Data Work?
Spring Data Code Example
Core Concepts
Summary
Part II: SQL Persistence
Chapter 4:Persistence and Domain Model
JPA Configuration Using Annotations
Entity
Types of Relationships
Types of Inherence
Listening and Auditing Events
Validating the Schema
Summary
Chapter 5:Transaction Management
What Is a Transaction?
What Is ACID?
Isolation Problems
Isolation Levels
Locking Types
How Do These Concepts Work in Spring Data?
Transactional Properties
Transaction Template
Optimistic Locking
Summary
Chapter 6:Versioning or Migrating Changes
Versioning Changes in a Database
Libraries That Implement Versioning
Which Library Does the Versioning?
Integrating Libraries in Spring Boot
Best Practices
Feature Flags
Implementing Feature Flags
Best Practices
Summary
Part III: NoSQL Persistence
Chapter 7:Redis:Key/Value Database
What Is Redis?
Spring Data Structures
Database and Connection Settings
Connecting with Primary/Secondary Nodes
Object Mapping and Conversion
Defining Custom Repositories
Queries by Example
Summary
Chapter 8:MongoDB:Document Database
What Is a Document Store?
Possible Uses Cases
Implementations
What Is MongoDB?
Introduction Spring Data Mongo
Database and Connection Settings
Access Using Repositories
Defining Queries
Using MongoTemplate with Custom Repositories
Summary
Chapter 9:Neo4j:Graph Database
What Is a Graph Database?
Possible Uses Cases
Implementations
What Is Neo4j?
Introduction Spring Data Neo4j
Database and Connection Settings
Access Using Repositories
Summary
Chapter 10:Cassandra:Wide-Column Database
What Is Cassandra?
Structure
Configuration
Database and Connection Settings
Defining Custom Repositories
Defining a TTL
Summary
Part IV: Advanced testing and best practices
Chapter 11:Reactive Access
What Is Reactive Access?
Modifying Queries to Be Reactive
Non-Relational Databases
Relational Databases
Considerations
Summary
Chapter 12:Unit and Integration Testing
Unit Testing with Mocks
Integration Testing with a Database
Testcontainers
Testcontainers vs.Embedded
Using Testcontainers
Multiple Integration Tests
Initialization Strategies
Potential Problems
Summary
Chapter 13:Detecting Performance Issues
Low-Performance Problems
Detecting Problems
Analyzing Query Performance
Analyzing Query Complexity
Checking the Performance of an Endpoint
Summary
Chapter 14:Best Practices
Compressing Information
Reducing Transferred Information
Using Optional in Custom Queries
Using Lazy in Relationships
Persisting Multiples Elements
Using Master/Slave or Replicas
Using Cache to Reduce Access
Summary
Appendix A:Setting up Environment Tools
Appendix B:Recommended and Alternative Tools
Appendix C:Opening a Project
Appendix D:Install and Configure a Relational Database
Appendix E:Installing and Configuring Non-Relational Databases
Appendix F:Further Reading
Index
About the Author
Andres Sacco
has been a professional developer since
2007, working with a variety of
languages, including Java, Scala, PHP,
Node.js, and Kotlin. His background is
mostly in Java and its libraries or
frameworks, like Spring, JSF, iBATIS,
Hibernate, and Spring Data. He is
focused on researching new technologies
to improve the performance, stability,
and quality of the applications he
develops.
In 2017 he started finding new ways
to optimize data transference between
applications to reduce infrastructure costs. He suggested actions
applicable to microservices. As a result of these actions, the cost was
reduced by 55%. Some of these actions are connected directly with the
harmful use of databases.
About the Technical Reviewer
Manuel Jordan Elera
is an autodidactic developer and
researcher who enjoys learning new
technologies for his experiments and
creating new integrations. Manuel won
the Springy Award 2013 Community
Champion and Spring Champion. In his
little free time, he reads the Bible and
composes music on his guitar.
Manuel is known as dr_pompeii. He
has tech-reviewed numerous books,
including Pro Spring MVC with WebFlux
(Apress, 2020), Pro Spring Boot 2
(Apress, 2019), Rapid Java Persistence
and Microservices (Apress, 2019), Java
Language Features (Apress, 2018),
Spring Boot 2 Recipes (Apress, 2018), and Java APIs, Extensions and
Libraries (Apress, 2018).
You can read his detailed tutorials on Spring technologies and
contact him through his blog at
www.manueljordanelera.blogspot.com . You can follow
Manuel on his Twitter account, @dr_pompeii.
Footnotes
1 https://spring.io/
2 http://jdk.java.net/
3 https://maven.apache.org/
4 https://www.eclipse.org/downloads/
5 https://www.jetbrains.com/es-es/idea/
6 https://code.visualstudio.com/
7 https://www.postgresql.org/
8 https://www.mongodb.com/es
9 https://redis.io/
10 https://neo4j.com/
11 https://cassandra.apache.org/_/index.xhtml
12 https://www.docker.com/
13 https://docker-curriculum.com/
14 https://michaelhaar.dev/my-docker-compose-cheatsheet
15 https://snyk.io/jvm-ecosystem-report-2021/
Part I
Introduction
Introduction
Spring Data is a vast topic that needs to be learned step by step. During
this first part, you will learn the basic concepts of accessing a database
without using a particular Spring module. The idea is that you see the
pros and cons of each mechanism to better understand why Spring
Data is a good solution. Also, you will see the different patterns and
solutions that are language- and library-agnostic, and therefore can be
applied to any framework or module.
The main goal of Part I is to teach you the basics of Spring and how
to create a basic Spring Boot project using IDE, CLI, or the website. You
will learn how to create a simple endpoint that persists information in a
relational database and use this basic application throughout the book,
changing only the type of database.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
A. Sacco, Beginning Spring Data
https://doi.org/10.1007/978-1-4842-8764-4_1
1. Application Architecture
Andres Sacco1
Persistence is typically one of the most important topics in any language because it provides a way
to save information in the long term for the applications that consume or produce it. In the past,
when developers created a single extensive application, problems tended to appear in one place.
Perhaps most of the logic resided in stored procedures, but when microservices emerged and
became an industry standard, most need to save their information. Hence, a topic’s importance
grows more than before with monoliths. Also, during the transition from monoliths to
microservices, many non-relational databases are an alternative to solve specific problems, like
the cache mechanism for saved information with a different structure.
Since Java was introduced, several ways to access information and other types of architecture
have appeared. This chapter overviews the evolution of ways to access a database and the pros
and cons.
Also, you learn some of the most relevant patterns associated with persistence in relational or
non-relational databases.
JDBC
JDBC, or Java Database Connectivity , provides a common interface to communicate and interact
with other databases. More concretely, JDBC offers a way to connect with a database, create and
execute statements like creating/dropping/truncating tables, and execute queries like
SELECT/INSERT/UPDATE/DELETE. Figure 1-2 shows a brief overview of the different
components that interact in the communication with a database using JDBC.
Interacting with a database has a set of components or layers .
JDBC API: This layer contains all the interfaces that all the drivers need to implement to allow
the Java developers to use them. This layer is one of the most important because you can change
from one database to another without changing many things, only the driver of the other
database and little changes in the type of columns.
JDBC Driver Manager: This set of classes acts as connectors between the drivers and the JDBC
API, registering and deregistering the available databases, obtaining the connection with
databases, and the information related to that connection.
Drivers: To make the connection between databases, JDBC hides all the logic related to the way
to interact with one database in a series of drivers, each of which contains the logic for one
database. Typically, the companies that develop these databases create the drivers for most
languages .
JDBC is not something that has not evolved since the first version in 1997. The subsequent
versions try to add more features or solve problems connected with the performance (see Table 1-
1). Frameworks like Spring implement a version of JDBC with some of the features of that
framework.
This table shows the evolution of JDBC and the specifications that explain in detail which
things introduce each version. Some of the first versions did not have concrete specifications.
JDBC Driver
The JDBC driver component implements the interfaces defined in the JDBC API to interact with a
database. Think of this component as a client-side adapter to convert one database’s specific
elements or syntax into the standard that Java can understand.
JDBC offers four recommended types in different situations, as illustrated in Figure 1-3.
Figure 1-3 Driver types that offer JDBC
3. Execute the query. Create an object Statement that contains the query to execute in a
database.
4. Obtain the data. After executing the query in a database, you need to use ResultSet.getXXX()
method to retrieve the information of each column.
5. Close the connection. You need to explicitly close the connection to a database in all cases
without considering if the application produces an exception or not.
Let’s look at all the concepts related to accessing a database and obtaining certain information.
The idea is to create a table structure that represents a catalog of countries/states/cities, which
you use in the chapters on relational databases . Figure 1-4 shows the structure of the tables with
the different relationships between them.
Note You can find the structure and the insert to populate the information of these tables,
along with all other source code, at github.com/apress/beginning-spring-data.
When everything looks fairly similar in your database, as in Figure 1-4, you can connect to a
database and obtain a list of the countries that exist using a block of code similar to the following .
package com.apress.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
EJB
Enterprise JavaBeans, or EJB , is a specification for building portable, scalable, and reusable
business applications without reinventing the way to do certain common things like security,
access to a database, sending messages across different applications, and many more. In the first
versions of Java, some of these features existed in other libraries or a basic version inside the JDK,
so when EJB emerged, unify all these features in the same framework.
One of the biggest differences with the previous approach of using JDBC to access a database is
you need an EJB container that runs inside an application server like Glassfish,4 Wildfly,5 and
Jetty.6 Figure 1-5 shows some of the most relevant features that EJB provides.
EJB has had multiple versions since 1999, introducing many new features, improving
performance, and fixing bugs from the previous version. Recently, EJB was adopted in Jakarta EE
in versions 8 and 9. Table 1-3 describes the most relevant things in7 each version.
Figure 1-7 Example of the structure of layers using JPA
EJB Types
The architecture of EJB has three main components: the EJB container, the application server, and
the Enterprise JavaBeans (EJB), which are split into various types .
Session beans: These components contain all the logic related to a user task or use case. The
session bean is available during the execution of that task or uses case like a conversation. But,
if the server crashes or restarts, all the information that resides inside the session bean is lost.
There are two types of session beans: stateful and stateless. The main difference is that the
first saves the states after someone calls it, and the second (stateless) does not save any
information after the invocating.
Message-driven beans: The previous beans work fine when you want synchronous
communication between applications, but message-driven beans are the correct option if you
need asynchronous communication. The most common implementation uses JMS (Java Message
Service )14. This type of EJB acts as a listener in a topic of a queue waiting for a message and
doing something when the message arrives. This type of communication became popular when
microservices appeared.
Entities: This component has classes that represent tables and provide an interface for CRUD
(create, retrieve/read, update, delete ) operations in a database. EJB 3.0 introduced a change in
this type of component to use JPA instead of the previous entities-beans, which are part of the
EJB specification.
Figure 1-6 shows the interaction between the components forming part of the EJB.
JPA
The Java Persistence API , or JPA, is a specification15 connected directly with the persistence into
databases. To be more specific, JPA provides a set of interfaces that all the providers need to follow
to guarantee that there are following the standard so you can change the provider without too
much effort.
Using JPA, developers can access the information in a database and execute certain operations
like insert, update, delete and retrieve using a Java class that represents the structure of the tables.
To do these operations, you need to annotate the classes with annotations representing the most
common things in a table, such as the table name, column size, and the relationship between
tables.
JPA offers several ways to do the queries to retrieve the information. One is using a SQL
statement directly like JDBC with classes to help construct the sentence, and another introduces
an abstraction so that you don’t need to write the entire sentence because the provider of JPA
generates the sentence dynamically. Figure 1-7 shows the different layers or the structure of JPA
with an application.
This specification has many implementations, but the most relevant are Hibernate,16
EclipseLink ,17 Apache OpenJPA ,18 and Spring Data JPA.19 Each of them implements the
specification of JPA but differently, prioritizing things like the performance or the developer
experience.
Let’s look at an example where you can declare a class representing one table in a database .
package com.apress.jpa.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity // Required
@Table(name = "currency") //Optional only if you need to indicate the
name
public class Currency {
The way to indicate the name and the length of the columns is not so complicated. If you do
not indicate the name and the size by default, the implementation of JPA defines the values, which
is 255 in the string.
Note You learn more about JPA in Part II of this book.
Spring Data
The main problem with all the previous mechanisms of persistence is you don’t have the chance to
access both types of databases, relational or non-relational. But Spring Data solves this problem ,
allowing you to access databases using repositories with an interface to do CRUD operations. Also,
you can create concrete that implements the repository interfaces with the idea of doing specific
operations not covered by the Spring Data framework. These repositories are available in almost
all implementations to access databases to reduce the complexity of using multiple databases in
the same application. There are basic repositories that you use to extend the functionality of your
repositories. In particular, two are most relevant. CrudRepository has the basic operations for all
the entities. PagingAndSortingRepository contains all the logic to obtain the information of one
structure in a database using the criteria of pagination and sorting.
Figure 1-8 illustrates that Spring Data supports MongoDB, Redis, Neo4j, Cassandra, and all the
relational databases. Others, like ElasticSearch 20 and Couchbase,21 are not covered in this book
because they have a similar structure for saving information.
Note In some databases, Spring Data provides a way to allocate and translate exceptions in a
database using templates used behind the scenes for the repositories or DAO to do certain
operations like insert or retrieve information. Spring Data JPA is excluded from the use of
Templates because it’s an abstraction to access all the RDBMS databases.
You can think of these templates to create custom repositories outside the basics that
Spring Data provides. For example, you can introduce security or a compression mechanism in
Redis before inserting or retrieving the information.
Object Mapping
One of the most significant advantages that JPA offers developers is the possibility to map a table
with a particular class considering all the possible types of columns and the relationship between
tables. Spring Data extends this approach to all NoSQL databases. Each type of database offers its
annotations to represent the information to map databases with Java classes. Table 1-4 shows that
each object could be represented in other databases without significant changes in the fields’
names and types. You only need to change the annotations related to each database.
JPA and Spring Data support mapping relationships between an object that could be stored in
another object (table, document, node). The annotations in Table 1-5 tell Spring Data about the
relationships among these objects and how to retrieve information.
Some databases do not have relationships, like Mongo in its first versions, but since version 3,
you can relate different entities. The idea behind this type of database is to reduce duplicate
information in entities .
Repository Support
When you write an application that needs to persist/retrieve information from a database, you
create a class or layer that contains all these operations in most cases. There are multiples ways to
group these operations: all together in the same class, one class per table, but the most common
way to do it is to create a class that represents the DAO pattern, which is discussed more in the
next section, with all the operations of one table. This means that you can have multiple classes to
access the database, where the main difference is the table you access. To reduce the complexity of
having multiple classes with the same code, Spring Data offers the possibility to use an abstraction
that contains all these operations, and you only need to indicate the name of the entity/table that
you access.
Spring Data offers interfaces that provide common database operations. You need to create an
interface that extends from one of that common interfaces and indicate which table or structure
you want to access. Behind the scenes, Spring Data transforms this interface into one query to
save/retrieve the information depending on the type of database. Figure 1-9 illustrates combining
interfaces to have more operations available which is covered in more detail in Part II of this book.
Figure 1-9 Example repositories that extend default Spring Data methods
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Le Voyage du
Centurion
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: French
LE VOYAGE
DV
CENTVRION
Et respondens centurio, ait : Domine, non
sum dignus ut intres sub tectum meum ; sed
tantum dic verbum, et sanabitur puer meus.
Nam et ego homo sum sub potestate
constitutus, habens sub me milites, et dico huic :
Vade, et vadit ; et alio : Veni, et venit ; et servo
meo : Fac hoc, et facit.
PARIS
LOUIS CONARD, LIBRAIRE-ÉDITEUR
6, Place de la Madeleine, 6
MCMXXII
TOUS DROITS RÉSERVÉS
DU MÊME AUTEUR
A LA MÊME LIBRAIRIE
Terres de Soleil et de Sommeil, préface de Mgr Le Roy, 1
volume in-18 6 »
L’Appel des Armes, préface de Mgr Baudrillart, de
l’Académie française, 1 vol. in-18 6 »
Les Voix qui crient dans le Désert, préface du Général
Mangin, 1 vol. in-18 6 »
Voici un très beau livre et qui redoublera, chez tous les lettrés, la
douleur que leur a causée, il y a quinze mois, la mort prématurée de
son auteur, le lieutenant Ernest Psichari, héroïquement tombé en
Belgique, lors de la retraite de Charleroi. Son premier roman, l’Appel
des Armes, avait produit, on se rappelle, une sensation très vive.
Deux raisons y contribuèrent. Ernest Psichari était le petit-fils
d’Ernest Renan et le contraste de sa pensée avec la pensée de son
grand aïeul ne pouvait manquer d’étonner. Mais, surtout, c’était la
révélation d’un talent déjà supérieur et d’une nouveauté singulière,
où le don d’expression aiguë, l’hallucination continue de l’artiste
visionnaire s’associait à une subtilité d’analyse psychologique
incomparable. L’Appel des Armes nous racontait la simple histoire
d’un officier, Nangès, guérissant un jeune soldat des pires
intoxications anarchistes et pacifistes par la seule suggestion de sa
personnalité. Peu d’événements, un récit uni, j’allais dire terre à
terre, et c’était un portrait dressé en pied, d’un si haut relief que ce
Nangès reste, pour moi, à l’heure présente, aussi vivant que si je
l’avais connu en chair et en os. Il y avait là, entre autres pages, une
conversation entre camarades de garnison sur le métier de soldat,
égale par l’accent et supérieure par la portée au morceau justement
célèbre de Vigny dans le second chapitre de Servitude et Grandeur
qui commence : « L’armée est une nation dans la nation… » Vigny
ajoute : « C’est un vice des temps. » Pour Nangès, au contraire,
porte-parole avoué du romancier, le plus précieux travail du soldat
est de constituer, dans la nation, un type à part. Il représente, et
seul, un principe d’obéissance, de sacrifice et de danger, aussi
nécessaire à la tonicité générale de la Société que les sécrétions de
telle ou telle glande peuvent l’être à l’énergie générale de
l’organisme. Le soldat serait alors une de ces espèces sociales que
le plus perspicace des observateurs, Balzac, démêlait déjà. « La
Société », disait-il dans la préface de la Comédie humaine,
« ressemble à la Nature. Elle fait de l’homme, suivant les milieux où
son action se déploie, autant d’hommes différents qu’il y a de
variétés en zoologie. Les différences entre un soldat, un ouvrier, un
oisif, un savant, un commerçant, un homme d’État, un marin, sont,
quoique plus difficiles à saisir, aussi considérables que celles qui
distinguent le loup, le lion, l’âne, le cheval. Il a donc existé, il existera
toujours des espèces sociales comme il existe des espèces
zoologiques… »
Cette étude du caractère propre au soldat faisait le thème de
l’Appel des Armes. Elle fait aussi celui de ce récit posthume auquel
son auteur avait donné ce titre énigmatique : Le Voyage du
Centurion. De ce roman, — car c’en est un, mais d’un type si neuf
que l’on hésite à employer ce mot, — l’écrivain a laissé deux
versions : l’une, rédigée à la première personne et sous forme
autobiographique ; l’autre, — et c’est celle que l’on va lire, — sous
forme de récit objectif. Le titre s’éclaire par les deux versets de saint
Mathieu mis en épigraphe : « … Et le Centurion répondit :
« Seigneur, je ne suis pas digne que vous entriez sous mon toit.
Mais dites un mot seulement, et mon fils sera guéri, — car, moi
aussi, je suis un homme qui obéit et à qui l’on obéit. Je dis à ce
soldat : « Va », et il va. Je dis à cet autre : « Viens », et il vient ; à
mon serviteur : « Fais ceci », et il le fait. » Vous êtes averti aussitôt :
ce nouvel essai de psychologie militaire est aussi un essai de
psychologie religieuse. Le romancier revendique le droit d’associer
l’Évangile et l’épée, en vertu d’un texte qui prouve qu’il peut, qu’il
doit y avoir une doctrine chrétienne de la guerre. Le Christ qui a dit
au riche : « Quittez vos richesses », ne dit pas au Centurion :
« Quittez votre service. » En écoutant ces paroles de discipline sans
les relever, il les fait siennes. Que dis-je ? Il admire celui qui les
prononce. Audiens autem Jesus miratus est… Il ajoute : « Je n’ai
jamais trouvé autant de foi dans Israël. » C’est donc le soldat croyant
qu’Ernest Psichari va nous peindre. Il ne se propose pas de tracer
uniquement un tableau de mœurs, quoique ce tableau s’y trouve et
que les traits en soient d’un réalisme qui ne recule pas devant la
brutalité. Étant lui-même un professionnel, le romancier aime
l’humble détail du service, mais il en aime plus encore le sens
spirituel, ou mieux, il ne les sépare pas, et c’est la particularité qu’il
faut comprendre pour bien entrer dans l’esprit de ce récit.
Déjà, dans l’Appel des Armes, il était parlé de la « Mystique » du
métier militaire. Cette expression n’est pas spéciale à Psichari. Dans
les derniers travaux qu’il a donnés aux Cahiers de la Quinzaine,
Péguy l’employait sans cesse, et c’est à Péguy qu’est dédié l’Appel
des Armes. Cette formule décèle un état mental qui semble avoir été
celui de toute une élite de la jeunesse française avant 1914 et la
terrible guerre. L’épreuve actuelle ne peut que l’avoir accentué. La
Mystique ? — Je cherche le mot dans le dictionnaire et je trouve
cette définition : « qui a un sens caché, relatif aux mystères de la
foi ». Suit un exemple tiré d’une lettre de Pascal à M lle de Roannez :
« Il y a deux sens parfaits, le littéral et le mystique. » Quand Péguy
reproche aux adeptes de tel ou tel parti de manquer à la Mystique de
leur doctrine, quand Psichari fait dire à Nangès que l’Armée a sa
morale à elle et sa Mystique, ils entendent bien affirmer que notre
activité, pour être complète, doit avoir un sens caché et impliquer
une foi. Dans toute action humaine, ils discernent deux éléments :
une application positive extérieure à l’homme et une signification
secrète qui lui est intérieure. Le soldat fait la guerre. C’est
l’application extérieure. Il développe en lui secrètement, il porte à
leur maximum de tension certaines vertus. Il nourrit, il enrichit son
âme à travers son métier. C’est le travail intérieur. La vie de l’âme
devient alors la raison profonde et dernière de l’effort, même le plus
technique. L’acte de foi est là, dans cette affirmation que le monde
spirituel, non seulement est une réalité, mais qu’il est la réalité par
excellence. En dehors de lui, l’énergie la mieux adaptée de l’homme
le plus intelligent ne diffère pas du labeur de l’araignée tendant sa
toile. George Eliot parle dans Silas Marner d’un moment où son
héros, le tisserand de Raveloe, ayant perdu toute croyance, mais
infatigable à sa besogne, commence à mener une existence
d’insecte, — insectlike life. Cette mécanisation de l’être, un Péguy,
un Psichari la reconnaissent aussi bien dans la curiosité du savant,
dans les calculs du politicien, dans le libertinage du voluptueux, que
dans l’esclavage du bureaucrate ou du tâcheron. C’est contre elle
qu’ils font appel aux puissances du psychisme supérieur les plus
hautes tout ensemble et les plus profondes de notre personne.
Ouvrez le Voyage du Centurion, et, dès la première page, observez
sous quel jour le romancier vous présente son personnage,
Maxence, officier de tirailleurs, en train de conduire en Mauritanie
une colonne de méharistes : « … Son père, — le colonel lettré,
voltairien et pis, traducteur d’Horace, excellent et honnête vieillard,
homme enfin de belles façons, — s’était trompé. Maxence avait une
âme. Il était né pour croire, et pour aimer, et pour espérer. Il avait
une âme, faite à l’image de Dieu, capable de discerner le vrai du
faux, le bien du mal… Pourtant, cet homme droit suivait une route
oblique, une route ambiguë, et rien ne l’en avertissait, si ce n’est ce
battement précipité du cœur, cette inquiétude… » Vous posez le
livre, et, si vous êtes de ceux qui ont eu leurs vingt ans il y a trente
ans, vous vous rappelez comment pensait et sentait votre
génération. Elle oscillait entre l’intellectualisme à outrance et
l’arrivisme. On était scientiste et moniste, donc nihiliste, ou bien
brutalement ambitieux d’après Rastignac et Julien Sorel. Quel
chemin parcouru en un quart de siècle, et de quels retours la pensée
d’une race demeure capable ! Comme ces reprises de sève
déconcertent les inductions les mieux appuyées, les prophéties les
plus justifiées ! Soyons très prudents à ranger parmi les puissances
du passé les idées et les émotions dont nos pères ont vécu. Leur
vertu est-elle épuisée ? Nous ne le saurons jamais.
II
C’est un de ces retours inattendus que raconte le Voyage du
Centurion, le bouillonnement, à nouveau, dans une intelligence et
une sensibilité, d’une source qui paraissait tarie. L’Appel des Armes
nous avait dit la vocation militaire et dans quel moule psychologique
prend son relief, si l’on peut s’exprimer ainsi, ce type humain d’une
frappe très spéciale qu’est le soldat. Le Voyage du Centurion nous
dit l’éveil du croyant dans ce soldat, et comment la religion de la
consigne mène ce fervent de la discipline à toutes les disciplines.
Mais d’abord, pourquoi le Centurion ? Par rappel de l’épisode de
l’Évangile que j’ai déjà cité. Pourquoi le Voyage ? Parce que ce livre
est réellement le récit d’un voyage, le journal, étapes par étapes,
d’une expédition en Mauritanie. Le lieutenant Maxence se met en
marche pour le désert avec une troupe dont l’évocation fait les
premières lignes du livre : « … Il dépassa successivement l’arrière-
garde qui était un petit groupe compact de méharistes noirs, puis la
cohue des domestiques, cuisiniers et marmitons, puis les
mitrailleuses oscillant sur l’arête aiguë des dos de mulets, puis le
lourd convoi des chameaux porteurs de caisses, puis les cavaliers,
de grands nègres écrasant les petits chevaux du fleuve, les
méharistes maures drapés dans de larges gandourahs, puis, enfin,
l’avant-garde, au milieu de laquelle Maxence distingua son
interprète, un Toucouleur admirablement vêtu de soies brodées. Et
devant, il y avait la terre, la terre scintillante, givrée de soleil, la terre
sans grâce et sans honneur où errent, sous des tentes en poils de
chameau, les plus misérables des hommes… » J’ai tenu à citer ce
quadro comme un échantillon de la manière de l’écrivain, de son
coloris si pittoresque et si vrai. On comprendra tout de suite
l’originalité singulière du roman, si j’ajoute que ce Voyage est aussi
le pèlerinage d’une pensée, la randonnée à travers ses propres
idées d’un esprit à la recherche d’une certitude, d’une conscience en
quête d’une règle surnaturelle, d’un cœur en tourment de Dieu et de
l’Église. Vous tournez quelques pages, et vous rencontrez, écrites
de cette même plume de soldat impressionniste, des phrases
comme celles-ci : « Pourquoi donc, si Maxence est un soldat de
fidélité, pourquoi tant d’abandons qu’il a consentis ? Tant de
reniements dont il est coupable ? Pourquoi, s’il déteste le progrès,
rejette-t-il Rome, qui est la pierre de toute fidélité ? Et s’il regarde
l’épée immuable avec amour, pourquoi donc détourne-t-il ses yeux
de l’immuable croix ?… »
Il y a donc dans ce roman, et ce raccourci schématique suffit à le
montrer, deux romans parallèles : celui de l’officier en marche sur un
sol ennemi, qui scrute l’espace, scrute ses hommes, campe ici,
ailleurs se bat, qui veille, interroge, commande, tend sa volonté à
l’action, et il y a le roman du négateur qui souffre dans la foi absente
comme il souffrirait dans un membre mutilé. Il a quitté la France et
Paris pour servir, mais aussi pour échapper à une atmosphère
d’anarchie intellectuelle et sentimentale où il étouffait. Il est venu
demander à l’Afrique un emploi utile de ses trente ans, mais aussi
une réparation, un rétablissement de sa vie intérieure, par le danger,
par la solitude, par le contact quotidien avec une nature vierge et
des hommes primitifs. Étant soldat, il agit, et quelle action, celle qui
implique la responsabilité la plus poignante, puisqu’il représente la
Patrie ! Et ce chef d’une patrouille dans le désert réfléchit, de la
réflexion la plus individuelle, la plus solitaire, la plus semblable à
l’oraison mentale par le reploiement, la retenue et la garde des sens.
Les maîtres de la spiritualité reviennent sans cesse sur ce point. Un
saint Bonaventure donne à la méditation religieuse pour première loi
la rupture avec le monde extérieur : Sensuum revocatio ab
exterioribus, et un saint Nil : « Non poteris orare terrenis negotiis et
curis implicatus. Tu ne pourras pas prier, embarrassé des affaires et
des soucis de la terre. » Il semble donc que le Centurion de ce
Voyage doive apparaître comme un paradoxe impossible, comme la
fantaisie d’un artiste littéraire hanté par le désir de juxtaposer des
contradictoires. Entre parenthèses, ces mosaïques sont quelquefois
des chefs-d’œuvre, ainsi les Misérables, de Hugo. On sent tout de
même de pareils livres factices par un point. Ici rien d’artificiel. Tout
est exact et juste. Vous lisez quelques pages de ce livre, et vous
êtes pris aussitôt par cet accent de la réalité sentie qui ne s’imite
pas. Nous qui avons connu Ernest Psichari, nous savons que
Maxence, c’est lui-même, que cette expédition d’Afrique, il l’a
réellement faite, que ces crises d’âme, il les a traversées. Nous
ignorerions tout de sa personne que nous dirions encore de ce récit
qu’il est vrai. Il emporte avec lui cette crédibilité totale, absolue, qui
est la première vertu du roman. Sans elle, les plus beaux miracles
de style et de composition sont non advenus. Rappelez-vous
Salammbô. Avec elle, toutes les insuffisances de facture sont
oubliées. Rappelez-vous les Trois Mousquetaires. C’est écrit à la va-
vite, inventé au rebours de l’histoire. Le lecteur ne peut pas ne pas y
croire, et à cause de cela, c’est un grand roman, tandis que
Salammbô n’est que le plus magnifique exemple de rhétorique de la
langue.
A quoi tient-elle, cette crédibilité, qui fait qu’à l’heure présente
nous disons couramment : un Don Quichotte, un Robinson et un
d’Artagnan, quelque différence qu’il y ait entre le génie d’un
Cervantès ou d’un Daniel de Foë et la facilité hâtive de
l’improvisateur Dumas ? A la vraisemblance ? Non, puisque les Trois
Mousquetaires, précisément, abondent en aventures de cape et
d’épée qui touchent au fantastique. A la logique ? Pas davantage. Je
citerais telle nouvelle de Mérimée dont la trame est serrée d’une
manière merveilleuse ; cette logique même donne la sensation du
« simili », du fabriqué. Pour qu’il y ait crédibilité, il faut, semble-t-il,
que l’auteur soit par-dessus tout de bonne foi, qu’il croie à l’histoire
qu’il raconte, avec une spontanéité, une naïveté complètes. C’était le
cas de Dumas pour ses bretteurs, le cas de Balzac pour ses usuriers
et ses duchesses, le cas de Walter Scott pour ses Jacobites et ses
sorcières. C’est le cas de Psichari pour son Centurion et ses
Africains. C’est son cas, en particulier, pour les angoisses et les
joies, les remords et les résolutions qu’il lui prête. Il ne se demande
pas si vous en douterez. Il ne cherche pas à vous justifier l’anomalie
vivante que peut représenter une pareille dualité : des
préoccupations d’un service en campagne et des méditations à la
Pascal alternant dans une même tête. Il n’a pas à résoudre
l’objection. Elle ne surgit pas devant ses yeux. Ce personnage est
son double. Pourquoi discuterait-il sa réalité ? Et il ne la discute pas.
Il vous la montre et vous la voyez avez lui, comme lui. Elle s’impose
comme un fait. Ce serait le comble de l’art si ce n’était la simplicité
même de la nature.
III
PA UL BO UR G ET.
Novembre 1915.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookmass.com