100% found this document useful (5 votes)
45 views

Download ebooks file Beginning Spring Data: Data Access and Persistence for Spring Framework 6 and Boot 3 Andres Sacco all chapters

Sacco

Uploaded by

gyselgabi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
45 views

Download ebooks file Beginning Spring Data: Data Access and Persistence for Spring Framework 6 and Boot 3 Andres Sacco all chapters

Sacco

Uploaded by

gyselgabi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Download Full Version ebookmass - Visit ebookmass.

com

Beginning Spring Data: Data Access and Persistence


for Spring Framework 6 and Boot 3 Andres Sacco

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

Discover More Ebook - Explore Now at ebookmass.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Pro Spring Security: Securing Spring Framework 6 and Boot


3–based Java Applications, Third Edition Massimo Nardone

https://ebookmass.com/product/pro-spring-security-securing-spring-
framework-6-and-boot-3-based-java-applications-third-edition-massimo-
nardone/
ebookmass.com

Practical Spring LDAP: Using Enterprise Java-Based LDAP in


Spring Data and Spring Framework 6 2nd Edition Balaji
Varanasi
https://ebookmass.com/product/practical-spring-ldap-using-enterprise-
java-based-ldap-in-spring-data-and-spring-framework-6-2nd-edition-
balaji-varanasi/
ebookmass.com

Practical Spring LDAP: Using Enterprise Java-Based LDAP in


Spring Data and Spring Framework 6 2nd Edition Varanasi
Balaji
https://ebookmass.com/product/practical-spring-ldap-using-enterprise-
java-based-ldap-in-spring-data-and-spring-framework-6-2nd-edition-
varanasi-balaji/
ebookmass.com

Encyclopedia of Mycology, Two Volume Set Óscar Zaragoza

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

Repairing Bertrand Russell’s 1913 Theory of Knowledge


Gregory Landini

https://ebookmass.com/product/repairing-bertrand-russells-1913-theory-
of-knowledge-gregory-landini/

ebookmass.com

The Challenge of World Theatre History 1st ed. Edition


Steve Tillis

https://ebookmass.com/product/the-challenge-of-world-theatre-
history-1st-ed-edition-steve-tillis/

ebookmass.com

Social Stratification: Class, Race, and Gender in


Sociological Perspective 4th Edition, (Ebook PDF)

https://ebookmass.com/product/social-stratification-class-race-and-
gender-in-sociological-perspective-4th-edition-ebook-pdf/

ebookmass.com

Constructing Quantum Mechanics, Volume One. The Scaffold:


1900■1923 1st Edition Anthony Duncan

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

Beginning Spring Data


Data Access and Persistence for Spring Framework
6 and Boot 3
Andres Sacco
Buenos Aires, Buenos Aires, Argentina

ISBN 978-1-4842-8763-7 e-ISBN 978-1-4842-8764-4


https://doi.org/10.1007/978-1-4842-8764-4

© Andres Sacco 2023

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 use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

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.

This Apress imprint is published by the registered company APress


Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
To my grandparents, who taught me the importance of always learning
new things
To my wife and children for supporting me while writing this book
Introduction
In the past, developers saved information in a relational database using
conventional methods like JDBC. It worked for a time—when systems
were small or not overly complex to maintain. Gradually, new
technologies like Ibatis and Hibernate emerged to reduce the
complexity of queries and facilitated access to different relational
databases, allowing developers to focus on creating great applications
instead of spending a lot of time figuring out how to connect to a
database or reduce the number of connections.
Soon after, many non-relational databases appeared, solving certain
problems even while others persisted. As a developer, one still needed
to use a database client and struggle with myriad performance issues
and/or bad practices.
Spring1 proved to be the solution to multiple problems, be it related
to dependency injection or how to intercept a method or class
before/after another method calls it. It’s no wonder the framework’s
developers created something to reduce the complexity involved in
using multiple databases (relational and non-relational). Spring Data
solves most of these issues, increasing developers’ performance and
ability to create new applications.
This book will cover the basics of creating an application that can
access multiple databases and demonstrate how you can do things in
different databases. Also, you will learn best practices to help reduce
inefficiencies in your applications.

Why This Book


So, why write a book about Spring Data and how to persist information
in different databases? Most developers use different databases to
persist different types of information; for example, some use Redis (a
possible mechanism of cache) or MongoDB (to save documents whose
structure could change in the future). My purpose in writing this book
was to explain Spring Data’s power and its best practices.
The following are some common questions associated with the use
of databases.
How can you optimize queries or the number of operations in a
database?
How do you create unit tests to validate that queries or changes work
properly?
How can you maintain a registry of all changes made to the database?
How can you evaluate if there is a problem related to the
performance of your query?
Which database is the best option for the project you’re working on?
These are just some of the questions I’ve tried to address
throughout the book.
Who This Book Is For
This book is for developers with a programming background in Java
who want to know how to persist information in different databases
and how to create tests to validate whether their application performs
as intended.

Note It is beyond the scope of this book to explain in-depth all


concepts related to the creation of queries.

You are not required to have previous experience using Spring or


Spring Data because I will show you how to create a project from
scratch with different layers, each with a specific purpose.
Prerequisites
You should have Java JDK2 17 or higher installed on your machine,
Maven3 3.8.1 or higher, and an IDE you are comfortable with. IDE
options include Eclipse,4 IntelliJ IDEA,5 and Visual Studio Code,6 but
many others exist. What matters is that you’re comfortable with it.
It’s important to note that most chapters of this book require
different types of databases, such as Postgres,7 MongoDB,8 Redis,9
Neo4j,10 and Cassandra,11 so to reduce the headache of installing these
databases on your machine, I recommend you install Docker12 and use
it to run all the databases.
The use and installation of Docker are outside the scope of this
book, but there are plenty of online tutorials13 and cheat sheets14 that
show the most common commands.
How Do I Check That I Have the Right Prerequisites?
After installing all the tools mentioned in the previous section, you
need to ensure that all of them are correctly installed before starting to
read through the book.
In Java, you need to run the following command.

% 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)

After that, you need to check whether your installed version of


Maven is correct by using the following command.

% 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

To reiterate, I think Docker is optimal for this book, but only


because it reduces the necessity to install different types of databases
on your machine.
Why These Prerequisites?
There are several reasons to choose certain prerequisites for a book.
Some of them are connected to a specific tool or version of Java that the
reader will feel comfortable with or is likely to have a lot of experience
using. In this book, the prerequisites are connected with an annual
survey conducted by Synk.io.15
This survey suggests that most developers use only LTS versions of
Java in production environments (i.e., Java 8/11/17). Also, the same
survey mentions that 76% of developers use Maven to manage
dependencies on at least some of their applications.
That said, note that all examples in this book can be translated into
Gradle with minimum changes.

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

(1) Buenos Aires, Buenos Aires, Argentina

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.

Why Persistence Is So Important


Persistent information is one of the most important aspects of microservices and applications .
You will lose everything if you don’t preserve the data when you deploy or restart or if something
happens to your system.
But there are other things you need to consider because they can affect the performance of the
entire platform, adding latency or errors. The following are some problems associated with the
inappropriate use or design of a database .
Incrementing the latency to execute the queries and obtain information for a database
Incrementing the usage of CPU/memory for access to a database for a wrong design in the way
to connect
Choosing the old version or the incorrect type of database for the kind of information to persist
There are many problems associated with persistence, but this book does not require you to
know all of them. A wrong decision or not understanding the pros/cons of each type of database
and how access to the information could affect your entire system.

The History of Persistence


In the applications suffers an evolution since the JDBC appears in JDK 1.1 passing to ORM and now
with the use of Spring Data which offers a standard interface to access different databases. Some
of them are relational instead another one are not relational.
There are many ways to persist information in databases. Considering that at least 50% of
developers use Spring Boot, according to Snyk reports,1 it seems logical that many of them use
Spring Data. Figure 1-1 shows the history of the persistence on Java until Spring Data appeared in
2011.
Most libraries that interact with databases are relevant today. All of them evolved over the
years. Some interact with others; for example, Enterprise JavaBeans (EJB) and Java Persistence
API (JPA) are two different things in Figure 1-1. The first versions of EJB contained all JPA
specifications, which grew in relevance. EJB version 3.0 appears as two separate things that
interact between them.

Figure 1-1 History of persistence

Figure 1-2 Structure of JDBC

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.

Table 1-1 Evolution of JDBC by Version

Year Version Specification JDK Version


2017 JDBC 4.3 JSR 221 9
2014 JDBC 4.2 JSR 221 8
2011 JDBC 4.1 JSR 221 7
2006 JDBC 4.0 JSR 2212 6

2001 JDBC 3.0 JSR 543 1.4


1999 JDBC 2.1 1.2
1997 JDBC 1.2 1.1

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

Type 1: The JDBC-ODBC Bridge


This type was adopted for the first JDBC drivers because most databases initially supported ODBC
access . This driver converts JDBC into ODBC and vice versa acting as an adapter independent of
the database. You can think of this as a universal driver that is part of the JDK, so you don’t need to
include any dependency in your project.
This type of driver is only used for developing or testing; it is not used in production
environments because of problems related to the performance of converting from JDBC to ODBC
and issues with security.
Type 2: Client Based
The next generation of drivers becomes more popular because it removes all the transformation
of JDBC into ODBC to do the calls directly using native libraries for each database vendor, which
usually reuses the existing C/C++ code to create the libraries.
The advantages include increased performance because there is no transformation between
various formats. There are some drawbacks; for example, the driver must be installed in the client
machine.
Type 3: Two-Tier Architecture
Two-tier architecture , network protocol, and pure Java driver with middleware all refer to the same
concept. This type uses JDBC, which uses a socket to interact with a middleware server to
communicate with a database. This middleware contains all the different databases’ drivers, so
installing everything on each machine is unnecessary.
The main problem of this approach is having a dedicated server to interact with databases,
which implies more transference of information, introducing a point of failure. Also, the vendors
need to rewrite, which are in C/C++ to pure Java.
Type 4: Wire Protocol Drivers
The wire protocol or native protocol driver is one of the most popular ways to connect directly
with a database. In this type, the driver is written entirely in Java and communicates with a
database using the protocol defined for each vendor.
This type offers many advantages, including having an excellent performance compared with
the previous one and not requiring that you install anything in the client or the server. But, the
main disadvantage is each database has a driver which uses different protocols.

How to Connect with a Database


There are several approaches , depending on the performance, like using a pool of connections.
The basic process to connect with a database consists of the following steps.
1. Import the classes. You must include all the classes required to use JDBC and connect with a
database. In most cases, all the classes exist in the java.sql.* package .

2. Open a connection. Create a connection using DriverManager.getConnection(), representing


a physical connection with a database.

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;

public class App {

static final String DB_URL =


"jdbc:postgresql://localhost:5432/catalog";
static final String USER = "postgres";
static final String PASS = "postgres";
static final String QUERY = "SELECT id, code, name FROM country";

public static void main(String[] args) {

// Open a connection and close it when finish the execution


// The use of try/catch in this way autoclose the resources
try(Connection conn = DriverManager.getConnection(DB_URL,
USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {

// Obtain the information of one row


while (rs.next()) {

// Retrieve the data by column


int id = rs.getInt("id");
String code = rs.getString("code");
String name = rs.getString("name");

System.out.println(String.format("ID: %s, Code: %s,


Name: %s", id, code, name));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Figure 1-4 The structure of the catalog database

Figure 1-5 Features that provide EJB


The DB_URL has a specific format connected to each database type. Each URL type is defined
in the specific database driver you need to include in your project before running the application.
Table 1-2 lists common JDBC URLs by database. If you don’t like to test this example with Postgres,
you can try with others for the list.
Figure 1-6 EJB Components and how to interact with JPA

Table 1-2 JDBC URL by Database

Database JDBC URL


PostgreSQL jdbc:postgresql://host:port/database?properties
SQL Server jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
Oracle jdbc:oracle:thin:[<user>/<password>]@//<host>[:<port>]/<service>
MYSQL jdbc:mysql://host:port/database?properties

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

Table 1-3 List of EJB Versions with Their Characteristics

Year Version Characteristics


• Introduces support to use Entity Beans for persistent objects
1998/1999 EJB 1.0
• Has a remote interface to access remotely, so in a way, EJB is portable
• Introduces the deployment descriptor in an XML which replaces a class that contains all
1999 EJB 1.1
the metadata
• Introduces compatibility with CORBA and other Java APIs
2001 EJB 2.08 • Clients in the same J2EE container could access another EJB using a local interface
• Appears JavaBeans Query Language, which gives developers a chance to do SQL queries
• Adds support to create web services using SOAP
• Introduces the possibility of having a timer service to have a cron to invoke certain
2003 EJB 2.19 services in a period of time
• Adds support to use ORDER BY, AVG, MIN, MAX, SUM, and COUNT operations in the EJB
query
2006 EJB • Appears the POJO (Plain Old Java Objects) as a replacement for the EJB Bean class
3.010 • Rewrites most of the code to use annotations instead of having a big file with the
configuration
• The remote and local interfaces no longer necessary to be implemented
Year Version Characteristics
• JPA entities were decoupled from the EJB container to use independently
EJB
2009 • EJB Lite runs multiple components in the same VM as an EJB client
3.111
EJB • Autocloseable interfaces
2013
3.212 • Adds more control over the transactionality of life-cycle interceptor methods .
• Deprecation of the EJBContext.getEnvironment() method
EJB
2020 • Removes methods relying on JAX-RPC
4.013
• Most packages in javax.ejb moved to jakarta.ejb

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 {

@Id //Required - Identify which is the primary key


@GeneratedValue(strategy = GenerationType.SEQUENCE) //Indicate
the way to generate the ID
private Long id;

private String code;


private String description;
private Boolean enable;

@Column(name = "decimal_places", length = 5) //Optional:


Indicate the name and the lenght of the column
private String decimalPlaces;

public Currency(Long id, String code, String description,


Boolean enable, String decimalPlaces) {
this.id = id;
this.code = code;
this.description = description;
this.enable = enable;
this.decimalPlaces = decimalPlaces;
}

// Setters and getters for all the attributes


//Override the hashCode and equals methods
}

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.

Figure 1-8 The structure of repositories depends on the database

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.

Table 1-4 Declaring Entities in Various Databases

JPA MongoDB Neo4j


@Entity
@Table(name = "currency")
public class Currency {
@Id
@Document( @NodeEntity public class
@GeneratedValue(strategy =
Currency
GenerationType.SEQUENCE) collection="currency) public class { @GraphId private
private Long id; Currency { @Id private Long Long id; private
id; @Field("decimal_places") private String
@Column(name =
String decimalPlaces; //Other decimalPlaces; //Other
"decimal_places", length =
attributes and set/get} attributes and set/get}
5)
private String
decimalPlaces; //Other
attributes and set/get
}

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.

Table 1-5 Declaring Relationships Among Objects in a Database

JPA MongoDB Neo4j


@Entity
@Table(name = "country")
public class Country {
@Document(
@Id
collection="country) @NodeEntity public class Country
@GeneratedValue(strategy public class Country { @GraphId private Long
= { @Id private Long id; @RelatedTo( type = "has",
GenerationType.SEQUENCE) id; direction =
private Long private List<Currency> Direction.OUTGOING) private
id; @OneToMany currencies; List<Currency> currencies; //Other
private List<Currency> attributes and set/get}
//Other attributes and
currencies; set/get}
//Other attributes and
set/get
}

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.

Title: Le Voyage du Centurion

Author: Ernest Psichari

Author of introduction, etc.: Paul Bourget

Release date: July 29, 2022 [eBook #68632]

Language: French

Original publication: France: Louis Conard, 1922

Credits: Laurent Vogel (This file was produced from images


generously made available by The Internet
Archive/Canadian Libraries)

*** START OF THE PROJECT GUTENBERG EBOOK LE VOYAGE


DU CENTURION ***
ERNEST PSICHARI

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.

Matth., VIII, 8-9.

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 »

IL A ÉTÉ TIRÉ DU VOYAGE DU CENTVRION

10 ex. numérotés 4 à 10 sur papier de Chine.


20 ex. — 11 à 30 — de Japon impérial.
10 ex. — 31 à 100 — de Hollande.
100 ex. sur papier vélin : non mis dans le commerce.

Copyright by Louis Conard, 12 Juin 1922.


PRÉFACE

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

Il ne suffit pas, pour qu’un livre soit beau, d’une beauté


supérieure, qu’il ait cette force du fait. Il est nécessaire que le fait ait
une valeur. Il en a toujours une quand, à travers lui, nous atteignons
le fond d’un cœur humain. Jamais je n’ai compris plus clairement
qu’en lisant ce Voyage du Centurion le prix de cette franchise
courageuse qui vous dit : « Je suis ainsi. » Par une loi qui déconcerte
au premier abord, plus nous sommes nous-mêmes avec intensité,
plus les autres se retrouvent en nous. La gamme des mentalités
n’est, en effet, pas très étendue, et dès que l’on entre dans la
psychologie profonde, ce n’est plus la variété que l’on rencontre,
c’est l’unité, c’est l’identité. Suivons l’analyste du Voyage dans ce
travail de creusement moral auquel il s’abandonne. Il s’est reconnu
soldat, et il se reconnaît maintenant, dès qu’il se heurte au milieu
dans lequel il doit agir, soldat français. Au départ pour le désert il se
disait bien : « C’est la France qui m’a donné, à moi, humble
lieutenant, cette immense contrée comme un parc où je puisse
m’ébattre et bondir, aller et venir, selon mon caprice et comme au
hasard de mon bon plaisir. » Et aussitôt il ajoutait : « Mais lui,
Maxence, n’avait envers sa patrie aucune reconnaissance… » Cri
étrange et qui serait blasphématoire, si, justement, ce Voyage du
Centurion n’était pas aussi une découverte de la France. Comme
beaucoup de jeunes gens de sa génération, Maxence n’a vu, à son
entrée dans la vie, qu’un coin très étroit de son pays et que des
mœurs très momentanées. Il a pris Paris pour la France, et pas
même, mais, dans Paris, quelques coteries où l’apparent raffinement
d’esprit dissimule mal l’indigence foncière. Partout il a senti le faux
semblant, l’imposture, le vide. Et voici qu’en Mauritanie, au bord de
cet empire colonial conquis par ses camarades, l’officier a l’évidence
de la valeur de sa race. Il éprouve qu’il fait partie d’un grand peuple.
Il éprouve aussi qu’il a devant lui un peuple différent. Différent ? mais
par quoi ? Par sa religion. Pour la première fois Maxence se rend
compte qu’encore aujourd’hui, la France, en présence de l’Afrique,
c’est l’Église en présence de l’Islam, la Croix dressée en face du
Croissant. « Qu’importe que Maxence soit triste ou mauvais ? Il est
l’envoyé de la puissance occidentale. Rien n’y peut faire, ce sont
vingt siècles de chrétienté qui le séparent des Maures. Cette
puissance dont il porte le signe, c’est celle qui a repris les sables de
l’Islam et c’est celle qui traîne l’immense Croix sur ses épaules. Elle
est la puissance de Chrétienté. » Apercevez-vous comme, en
poussant à fond l’analyse de son métier de soldat, le songeur
découvre en lui le chrétien et aussi par quelle nécessité intime les
deux romans, celui de la bataille et celui de la prière, se rejoignent,
s’unissent. Souvenez-vous maintenant des récits que nous font ceux
qui reviennent, en ce mois de novembre 1915, de la ligne de feu, et
de la solennité, du recueillement de ces messes dites dans les
tranchées. Le Centurion du Voyage n’a fait que démêler en lui plus
tôt le Croisé préfiguré dans tout ceux qui portent l’uniforme de
France. Chez les uns, il apparaît conscient comme chez lui. Les
autres ignoreront jusqu’à la fin ce caractère mystique de leur propre
action. Le Croisé est vivant dans tous. Il explique pourquoi la guerre
comprise à l’allemande nous cause une horreur qui nous révolte
dans nos fibres les plus secrètes. C’est que nous sommes les
soldats de la chrétienté, et que nous avons devant nous les soldats
d’Odin.
Arrivé à ce stade de sa réflexion, l’auteur du Voyage du
Centurion aurait pu s’arrêter. Le point de vue national est une variété
du pragmatisme. On sait que ce mot, — qui vient du grec
πραγματικος, relatif aux affaires, aux faits, — sert à désigner
aujourd’hui une apologétique uniquement fondée sur l’utilité. Il est
certain, en effet, que la vérité n’a pas pour mesure l’utilité ; il n’est
pas moins certain que l’utilité reste une présomption de vérité, en
sorte que le pragmatisme, erroné en tant que philosophie définitive,
est très légitime en tant que méthode et que commencement
d’enquête. Il n’est que la mise en œuvre du précepte sur les faux
prophètes : « Un arbre mauvais ne peut porter de bons fruits. Vous
les reconnaîtrez à leurs fruits. » C’est une première étape à laquelle
une âme sincèrement religieuse ne peut pas se tenir. L’action ne lui
suffit pas. Ou plutôt l’action, pour elle, n’est qu’un symbole d’une
réalité spirituelle que cette âme a besoin d’atteindre. Ernest Psichari
dit cela nettement. Son Maxence s’affirme bien que « devant l’Arabe,
il est un Franc, tenant sa certitude de sa race à tout jamais
consacrée… Et que serait sa fierté devant le Maure, sinon une fierté
catholique ? » Mais son historien, son frère, ajoute aussitôt : « Il reste
au fond de lui un sombre tourment. Que les faibles se nourrissent
des plus nobles rêves. Lui, il veut la vérité avec violence. Il est saisi
par la noble ivresse de l’intelligence, et cette fièvre de l’esprit le
travaille d’aller à la véritable raison, à cette espérance très sereine
de la raison bien assise. Il demande d’abord que Jésus-Christ soit
vraiment le verbe de Dieu, que l’Église soit, de toute certitude, la
gardienne infaillible de la vérité… »
Ici, je ne peux que renvoyer le lecteur au texte lui-même. Les
pages où Ernest Psichari raconte le dialogue de son Maxence, de
lui-même, avec Dieu dans le désert, rappellent par leur éloquence et
leur pathétique le célèbre Mystère de Jésus. Elles sont, à mon
jugement, parmi les plus belles dont puisse s’enorgueillir notre
littérature mystique. N’y cherchez pas plus de raisonnements
abstraits, de dialectique, d’exégèse que dans le quatrième livre de
l’Imitation. La vérité que cherche Maxence n’est pas une vérité
d’école. Elle ne s’apprend ni dans les bibliothèques ni dans les
laboratoires. C’est une vérité vivante, qu’il faut sentir en même
temps qu’on la comprend. C’est un rapport de l’Ame et de l’éternelle
Pensée, de l’éternel Amour, de l’éternelle Puissance. Je me suis
expliqué, en lisant ce magnifique finale, qu’Ernest Psichari m’ait écrit
dans une lettre qu’il m’adressait de sa garnison de Cherbourg, dans
l’hiver de 1914, et pendant qu’il achevait le Centurion : « C’est un
tremblement que d’écrire en présence de la Très Sainte Trinité. »
Mot bien étrange d’un jeune romancier à son aîné. Mot révélateur et
qui permet de comprendre ce que ce petit-fils de Renan demandait à
l’art littéraire : un apostolat de sensibilité sublime, un pain de vie à
distribuer aux cœurs, de quoi susciter la vertu du Sacrifice sanglant,
à la veille d’une crise qu’il pressentait tragique. Ce livre posthume
est comme le testament de cette grande âme. J’aurai, je crois, rendu
à son auteur le témoignage qu’il eût le mieux aimé quand j’aurai
conclu simplement que le Voyage du Centurion s’accorde à la mort
de celui qui l’a écrit. Ce sont deux actes de foi qui se ressemblent,
qui s’appelaient l’un l’autre. Le héros chrétien nous eût défendu de le
pleurer, « comme ceux qui n’ont pas d’espérance ». Comment lui
obéir et ne pas les laisser couler, ces impuissantes larmes devant
cette noble promesse brisée ?

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like