100% found this document useful (1 vote)
17 views

Beginning Spring Data: Data Access and Persistence for Spring Framework 6 and Boot 3 Andres Sacco instant download

The document promotes a collection of ebooks and textbooks focused on Spring Framework 6 and Boot 3, including titles like 'Beginning Spring Data' and 'Pro Spring Security.' It provides links to download these resources and emphasizes the importance of Spring Data for managing database interactions. Additionally, it outlines the structure and content of the book 'Beginning Spring Data,' which covers various aspects of data access and persistence in Java applications.

Uploaded by

hastirdujan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
17 views

Beginning Spring Data: Data Access and Persistence for Spring Framework 6 and Boot 3 Andres Sacco instant download

The document promotes a collection of ebooks and textbooks focused on Spring Framework 6 and Boot 3, including titles like 'Beginning Spring Data' and 'Pro Spring Security.' It provides links to download these resources and emphasizes the importance of Spring Data for managing database interactions. Additionally, it outlines the structure and content of the book 'Beginning Spring Data,' which covers various aspects of data access and persistence in Java applications.

Uploaded by

hastirdujan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Download the full version and explore a variety of ebooks

or textbooks at https://ebookmass.com

Beginning Spring Data: Data Access and Persistence


for Spring Framework 6 and Boot 3 Andres Sacco

_____ Tap the link below to start your download _____

https://ebookmass.com/product/beginning-spring-data-data-
access-and-persistence-for-spring-framework-6-and-
boot-3-andres-sacco/

Find ebooks or textbooks at ebookmass.com today!


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmass.com
to discover even more!

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/

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/

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/

Beginning Spring 6 Joseph B. Ottinger

https://ebookmass.com/product/beginning-spring-6-joseph-b-ottinger/
Spring 6 Recipes: A Problem-Solution Approach to Spring
Framework Marten Deinum

https://ebookmass.com/product/spring-6-recipes-a-problem-solution-
approach-to-spring-framework-marten-deinum/

Beginning Spring Boot 3 2nd Edition Siva Prasad Reddy


Katamreddy [K. Siva Prasad Reddy]

https://ebookmass.com/product/beginning-spring-boot-3-2nd-edition-
siva-prasad-reddy-katamreddy-k-siva-prasad-reddy/

Pro Spring 6: An In-Depth Guide to the Spring Framework,


6th Edition Iuliana Cosmina

https://ebookmass.com/product/pro-spring-6-an-in-depth-guide-to-the-
spring-framework-6th-edition-iuliana-cosmina/

Beginning Spring Boot 3: Build Dynamic Cloud-Native Java


Applications and Microservices - Second Edition K. Siva
Prasad Reddy
https://ebookmass.com/product/beginning-spring-boot-3-build-dynamic-
cloud-native-java-applications-and-microservices-second-edition-k-
siva-prasad-reddy/

Hacking with Spring Boot 2.3: Reactive Edition

https://ebookmass.com/product/hacking-with-spring-boot-2-3-reactive-
edition/
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
Figure 1-10 The basic structure of layers

Architectures Types
The applications generally have a structure that helps you to understand where you can find logic,
such as validations, business logic, entities, and the interfaces/classes to access a database. All of
them are important to understand the hierarchy of the layers and which rules you need to follow
to create a new feature or application.
In Java, tools like Archunit22 allow you to define and check if everything in your project follows
your defined structure.

Layers
This type of architecture is the simplest because it splits the application into different layers like a
cake where each layer can only access the elements to the same or the inferior level. These types
of architecture mutate from architecture with four layers like view/presentation, business logic,
persistence, and database to others with three or five. There is no universal criterion for the
correct number of layers. But, if you consider that three is a small number of layers, Spring Boot is
represented by controllers, services, repositories, and the database, which does not appear
directly in Spring as layers. Figure 1-10 shows a representation about this type of architecture and
how to interact the different layers.

Benefits
This structure has the following benefits.
It’s simple to implement and maintain because you only have a hierarchy of layers.
Each layer has only one responsibility and does not know how to implement the logic of the
other layers, so you can introduce modifications in the logic of layers that could not directly
affect others.
The structure is more or less the same in all the projects. You can change from one project to
another and know where to find something.

Drawbacks
This type of architecture has the following drawbacks.
Hiding the use cases, it’s difficult to know where all the classes or objects are connected to
represent a use case.
Depending on the size and the number of layers, you can have problems with scalability
because you can have several classes/interfaces in the same package or layer .

Note This book has no formal recommendation about which type of architecture you need to
use. But most examples follow the layers architecture.

Hexagonal
The layered architecture offers developers a simple way to create an application and understand
the separation of roles or responsibilities. In 2005, Alistar Cockburn23 proposed a new alternative
that encapsulates or keeps all external communication with databases or external systems
agnostic . To this, he created the concept of input/output in the architecture to represent
communication with external resources like databases or external systems.
The main idea of this type of architecture is to create all the business logic that isolates it from
the external tools and technologies that are irrelevant to how the application works. Figures 1-11
shows the different elements that have the hexagonal architecture and how to interact with
external resources like databases or other applications.
This architecture splits the hexagon into two parts. One part is called the “driving side,” where
the actors start the interaction, such as external systems and web/mobile systems. The other part
is the “driven side,” where the actors receive a request to obtain certain information from a
database or other external systems.

Components
The hexagonal architecture has several components inside each part of the structure, but I
mention only the most relevant for understanding the basic idea.
Infrastructure contains the port and adapters responsible for connecting with external
systems or databases using different protocols. The ports are interfaces agnostic to the
technology defining the methods to access the application or other systems. The adapters are
the implementation of the ports related to a specific technology, like a query to a database or a
REST controller.
Use cases are the core of the systems because it contains all the logic related to various
scenarios and how they are related. Depending on the author, this component receives other
names like application or domain layer and combines the use cases with the domain
component.
Entities are the pure domain of the application, with all the entities of value objects used in the
application component.

Benefits
This structure has the following benefits.
You can change or swap adapters without problems.
The domain and the use cases are pure, so you can understand the business logic.
You can change the implementation of the ports for testing purposes.

Drawbacks
This type of architecture has the following drawbacks.
Implementing some frameworks is difficult because you can make mistakes with what you
consider adapters/ports .
Introduce indirection to find the implementation of each port.
No guideline explains all the things about the organization of the projects, so anyone can
introduce something wrong.

Persistence Design Patterns


Throughout this book, some code responds to the same structure because patterns are associated
with access to a database. This section introduces the most relevant of these patterns, but there
are other ones this book does not cover, most of which are mentioned on Martin Fowler’s
website.24

Data Access Object (DAO)


A data access object (DAO) pattern persists and retrieves information for databases. It allows
developers to isolate the business layer for the persistence layer, which in most cases is associated
with a database but could be anything that has the responsibility of access to the information.
This pattern hides the complexity of performing all the CRUD operations into a database so
you can change or introduce modifications without significantly affecting all the rest of the layers.
It is not common in Spring Data because most developers use the repository pattern. But some
cases related to the performance or operations are not supported for that pattern, so the DAO
patterns appear to rescue us from the problem.
Figure 1-12 show how the different interfaces/classes interact to access the database
following this pattern.
When they start to use this pattern, most developers create a generic interface with all the
possible methods and create one class to access a specific table and reduce the number of files
connected with access to a database. Listing 1-1 shows the different methods that a common DAO
could have, of course, you can create other ones but most of the frameworks implement these
methods.
public interface CommonDao<T> {

Optional<T> get(long id);

List<T> getAll();

void save(T t);

void delete(T t);


}
Listing 1-1 A Common Interface to Access a Database
Now that you have seen a common interface, the implementation is more or less similar in all
cases. The difference relates to the name of the table and the queries to access a database, but all
the DAO respects the same format.
Listing 1-2 shows a possible implementation of the interface that appears on Listing 1-1; take
into consideration that there are other ways to do it.

public class CityDao implements CommonDao<City> {

private List<City> cities = new ArrayList<>();

public CityDao() {
cities.add(new City("BUE", "Buenos Aires"));
cities.add(new City("SCL", "Santiago de Chile"));
}

public Optional<City> get(long id) {


return Optional.ofNullable(cities.get((int) id));
}

public List<City> getAll() {


return cities;
}

public void save(City city) {


cities.add(city);
}

public void delete(City city) {


cities.remove(city);
}
}
Listing 1-2 Implementation of a Common DAO

Note Focusing only on the pattern example, there is no real connection between a database
and creating cities in the application's memory, but the concept is the same.

Repository Pattern
The repository pattern accesses a database to obtain certain information introducing an
abstraction for the rest of the layers. The spirit of the repository pattern is to emulate or mediate
between the domain and data mapping using interfaces to access the domain objects.
The main difference between the DAO and repository patterns is the repositories are next to
the business logic and try to hide all the logic related to the queries to a database. The most
common use is to create an interface containing certain methods; frameworks like Spring Boot
and Quakus transform the methods into specific queries to a database. In contraposition, the DAOs
implement all the logic using queries to access a database. See Table 1-6 to check the main
differences between the approaches.

Figure 1-11 Hexagonal architecture with the most relevant layers

Table 1-6 Main Differences Between DAOs and Repositories

DAO Pattern Repository Pattern


It’s closer to the database because dealing It’s closer to the business/domain layer because it uses
queries and tables. abstraction to hide the implementation.
DAOs could not contain repositories because
Repositories could contain or implement DAOs.
they are in different layers.
It’s an abstraction of the data. It’s an abstraction of a collection of objects.

Spring Data offers developers a basic interface to implement the logic of pagination and CRUD
operations without needing extra work . Listing 1-3 shows an example of an interface that follows
the repository pattern

interface CityRepository {

Optional<City> get(long id);

List<City> getAll();

void save(City city);

void delete(City city);


Other documents randomly have
different content
severally in every part of Nature: If the first, then I cannot conceive,
but all motion must be uniform, or after one and the same manner;
nay, I cannot understand, how there can be any dilation and
contraction, or rather any motion of the same spirit, by reason if it
dilate, then, (being equally spread out in all the parts of Matter,) it
must dilate beyond Matter; and if it contract, it must leave some
parts of matter void, and without motion. But if the Spirit moves
every part severally, then he is divisible; neither can I think, that
there are so many Spirits as there are Parts in Nature; for your
Author says, there is but one Spirit of Nature; I will give an easie
and plain example: When a Worm is cut into two or three parts, we
see there is sensitive life and motion in every part, for every part will
strive and endeavour to meet and joyn again to make up the whole
body; now if there were but one indivisible Life, Spirit, and Motion, I
would fain know, how these severed parts could move all by one
Spirit. Wherefore, Matter, in my opinion, has self-motion in it self,
which is the onely soul and life of Nature, and is dividable as well as
composable, and full of variety of action; for it is as easie for several
parts to act in separation, as in composition, and as easie in
composition as in separation; Neither is every part bound to one
kind or sort of Motions; for we see in exterior local motions, that one
man can put his body into several shapes and postures, much more
can Nature. But is it not strange, Madam, that a man accounts it
absurd, ridiculous, and a prejudice to Gods Omnipotency, to attribute
self-motion to Matter, or a material Creature, when it is not absurd,
ridiculous, or any prejudice to God, to attribute it to an Immaterial
Creature? What reason of absurdity lies herein? Surely I can
conceive none, except it be absurd and ridiculous to make that,
which no man can know or conceive what it is, viz. an immaterial
natural Spirit, (which is as much as to say, a natural No-thing) to
have motion, and not onely motion, but self-motion; nay, not onely
self-motion, but to move, actuate, rule, govern, and guide Matter, or
corporeal Nature, and to be the cause of all the most curious
varieties and effects in nature: Was not God able to give self-motion
as well to a Material, as to an Immaterial Creature, and endow
Matter with a self-moving power? I do not say, Madam, that Matter
hath motion of it self, so, that it is the prime cause and principle of
its own self-motion; for that were to make Matter a God, which I am
far from believing; but my opinion is, That the self-motion of Matter
proceeds from God, as well as the self-motion of an Immaterial
Spirit; and that I am of this opinion, the last Chapter of my Book of
Philosophy will enform you, where I treat of the Deitical Centre, as
the Fountain from whence all things do flow, and which is the
supream Cause, Author, Ruler and Governor of all. Perhaps you will
say, it is, because I make Matter Eternal. 'Tis true, Madam, I do so:
but I think Eternity doth not take off the dependance upon God, for
God may nevertheless be above Matter, as I have told you before.
You may ask me how that can be? I say, As well as any thing else
that God can do beyond our understanding: For I do but tell you my
opinion, that I think it most probable to be so, but I can give you no
Mathematical Demonstrations for it: Onely this I am sure of, That it
is not impossible for the Omnipotent God; and he that questions the
truth of it, may question Gods Omnipotency. Truly, Madam, I wonder
how man can say, God is Omnipotent, and can do beyond our
Understanding, and yet deny all that he is not able to comprehend
with his reason. However, as I said, it is my opinion, That Matter is
self-moving by the power of God; Neither can Animadversion, and
Perception, as also the variety of Figures, prove, that there must be
another external Agent or Power to work all this in Matter; but it
proves rather the contrary; for were there no self-motion in Matter,
there would be no Perception, nor no variety of Creatures in their
Figures, Shapes, Natures, Qualities, Faculties, Proprieties, as also in
their Productions, Creations or Generations, Transformations,
Compositions, Dissolutions, and the like, as Growth, Maturity, Decay,
&c. and for Animals, were not Corporeal Matter self-moving,
dividable and composable; there could not be such variety of
Passions, Complexions, Humors, Features, Statures, Appetites,
Diseases, Infirmities, Youth, Age, &c. Neither would they have any
nourishing Food, healing Salves, soveraign Medicines, reviving
Cordials, or deadly Poysons. In short, there is so much variety in
Nature, proceeding from the self-motion of Matter, as not possible to
be numbred, nor thorowly known by any Creature: Wherefore I
should labour in vain, if I endeavoured to express any more thereof;
and this is the cause that I break off here, and onely subscribe my
self,
Madam,
Your faithful Friend
and Servant.

XXIII.
MADAM,
Concerning the comparison, your Author makes between an
Immaterial Spirit, and Light,[1] That, as Light is contractive and
dilative, and yet not divisible, so is also an Immaterial substance.
Give me leave to tell you, that in my opinion, all that is contractive
and dilative, is also dividable, and so is light: As for example; when a
Candle is snuff'd, the Snuffers do not onely clip the wick, but also
the light: The like when a dark body is interposed, or crosses the
rays of the Sun; it cuts those rays asunder, which by reason they
cannot joyn together again, because of the interposed body, the
light cut off, suddenly goeth out; that is, the matter of light is altered
from the figure of light, to some other thing, but not annihilated:
And since no more light can flow into the room from the Fountain or
Spring of Light, the Sun, because the passage is stopt close, the
room remaineth dark: For Light is somewhat of the nature of Water;
so long as the Spring is open, the Water flows, and whatsoever is
taken away, the Spring supplies; and if another body onely presses
thorow it, it immediately joyns and closes its severed parts again,
without any difficulty or loss; The same doth Light; onely the
difference is, that the substance of Light is extraordinary rare, and
pure; for as Air is so much rarer then Water, so Light is so much
rarer and purer then Air, and its matter may be of so dilating a
nature, as to dilate from a point into numerous rayes. As for ordinary
Fire-light, it doth not last longer, then it hath fuel to feed it, and so
likewise it is with the light of the Sun; for Light is according to the
substance that feeds it; and though it is a substance it self, yet it
increases and decreases, according as it hath something that
succours or nourishes it. But some may object, that if Light were a
body, and did contract and dilate, as I say, it is impossible that it
could display it self in so great and vast a compass, and remove so
suddenly and instantly as it doth. To which objection, I answer, first,
That although I say, Light is a real corporeal substance, and doth
contract and dilate it self from a point into numerous rayes, as also
in another Letter I sent you before,[2] That Light and Darkness do
succeed each other; nevertheless, as for the perception of Light, I
am not so eager in maintaining this opinion, as if it was an Infallible
Truth, and impossible to be otherwise; but I say onely, That, to my
sense and reason, it seems very probable, that it may be so, that the
light of the Sun doth really dilate it self into so vast a compass as we
see, and that light and darkness do really succeed each other, as all
other Creatures do: But yet it seems also probable to mee, that the
parts of the Air may onely pattern out the figure of light, and that
the light we see in the Air may be onely patterns taken from the real
figure of the light of the Sun: And therefore, if it be according to the
former opinion, to wit, That the light of the Sun doth really dilate it
self into so vast a compass, My answer is, That contraction and
dilation are natural corporeal actions or motions, and that there is no
alteration of motion in Nature, but is done in Time, that is,
successively, not instantly; for Time is nothing else but the alteration
of motion: Besides, I do not perceive any so sudden and swift
alteration and succession of light, but that it is done by degrees: As
for example; in the morning, when it begins to dawn and grow light,
it appears clearly to our sight how light doth come forth, and
darkness remove by degrees; and so at night, when it grows dark,
how light removes, and darkness succeeds; nay, if there be any such
sudden change of the motions of Light, I desire you to consider,
Madam, that light is a very subtil, rare, piercing and active body, and
therefore its motions are much quicker then those of grosser bodies,
and cannot so well be perceived by our gross exterior senses. But if
it be, that the Air doth pattern out the light of the Sun, then the
framed objection can prove nothing, because there is not then such
a real dilation or succession of light, but the corporeal figurative
motions of the Air do make patterns of the light of the Sun, and
dissolve those patterns or figures again, more suddenly and quickly
then man can shut and open his eyes, as being more subtil then his
gross exterior senses. But it may be said, that if Air did pattern out
the light of the Sun, the light would increase by these numerous
patterns. I answer, that cannot appear to our Eyes; for we see onely
the pattern'd figure of light, and that a great compass is enlightned;
also that the further the air is from the Sun, the darker it is;
nevertheless, I do verily believe, that the body of the Sun is far
brighter then the light we see, and that the substance of light, and
the patterns taken from light, are not one and the same, but very
different. And thus much of light. As for Penetration, I conceive it to
be nothing else but division; as when some parts pierce and enter
through other parts, as Duellers run each other thorow, or as water
runs through a sieve. And this is the opinion of,
Madam,
Your faithful Friend,
and Servant.
[1] In the Append. to the Antid. c. 3. and Of the Immortality of
the Soul, l. 1. c. 5.
[2] Sect. 1. Let. 20.

XXIV.
MADAM,
Having given you my opinion, both of the substance and perception
of Light, in my last Letter, I perceive your desire is to know how
Shadows are made. Truly, Madam, to my sense and reason, it
appears most probable, that shadows are made by the way of
patterning: As for example; when a Man's, or Trees, or any other the
like Creature's shadow is made upon the Ground, or Wall, or the like;
those bodies, as the Ground, or Wall, do, in my opinion, pattern out
the interposing body that is between the light and them: And the
reason that the shadow is longer or shorter, or bigger or less, is
according as the light is nearer or further off; for when the light is
perpendicular, the interposing body cannot obscure the light,
because the light surrounding the interposing body by its brightness,
rather obscures the body, then the body the light; for the numerous
and splendorous patterns of light taken from the body of the Sun, do
quite involve the interposing body. Next, you desire to know,
Whether the light we see in the Moon, be the Moons own natural
light, or a borrowed light from the Sun: I answer, that in my opinion,
it is a borrowed light; to wit, that the Moon doth pattern out the
light of the Sun: and the proof of it is, that when the Sun is in an
Eclipse, we do plainly perceive that so much of the Sun is darkned
as the Moon covers; for though those parts of the Moon, that are
next the Sun, may, for any thing we know, pattern out the light of
the Sun, yet the Moon is dark on that side which is from the Sun. I
will not say, but that part of the Moon which is towards the Earth,
may pattern out the Earth, or the shadow of the Earth, which may
make the Moon appear more dark and sullen; But when the Moon is
in an Eclipse, then it is plainly perceived that the Moon patterns out
the Earth, or the shadow of the Earth. Besides, those parts of the
Moon that are farthest from the Sun, are dark, as we may observe
when as the Moon is in the Wane, and enlightened when the Sun is
nearer. But I will leave this argument to observing Astrologers, and
rest,
Madam,
Your faithful Friend
and Servant.

XXV.
MADAM,
If according to your Authors opinion,[1] In every particular world,
such as Man is especially, his own Soul (which is a Spirit) be the
peculiar and most perfective architect of the Fabrick of his Body, as
the Soul of the world is of it: Then I cannot conceive in my reason,
how the separation is made in death; for I see, that all animals, and
so man-kind, have a natural desire to live, and that life and soul are
unwilling to part; And if the power lies in the Soul, why doth she not
continue with the Body, and animate, move and actuate it, as she
did before, or order the matter so, as not to dissolve? But if the
dissolution lies in the body, then the body has self-motion: Yet it is
most probable, if the soul be the architect of the body, it must also
be the dissolver of it; and if there come not another soul into the
parts of matter, the body must either be annihilated, or lie immoved
as long as the world lasts, which is improbable; for surely all the
bodies of men, or other animals, are imployed by Nature to some
use or other: However, it is requisite, that the soul must stay so long
in the body, until it be turned into dust and ashes; otherwise, the
body having no self-motion, would remain as it was when the soul
left it, that is, entire and undissolved: As for example; when a man
dies, if there be no motion in his body, and the soul, which was the
mover, be gone, it cannot possibly corrupt; for certainly, that we call
corruption, is made by motion, and the body requires as much
motion to be dissolved or divided, as it doth to be framed or
composed; Wherefore a dead body would remain in the same state
continually, it had no self-motion in it: And if another soul should
enter into the body, and work it to another figure, then certainly
there must be many more souls then bodies, because bodies are
subject to change into several forms; but if the animal spirits, which
are left in the body after the soul is gone, are able to dissolve it
without the help of the soul, then it is probable they could have
fram'd it without the help of the soul; and so they being material, it
must be granted, that matter is self-moving: But if corporeal matter
have corporeal self-motion, a self-moving Immaterial Spirit, by
reason of their different natures, would make great obstruction, and
so a general confusion; for the corporeal and incorporeal motions
would hinder and oppose each other, their natures being quite
different; and though they might subsist together without
disturbance of each other, yet it is not probable they should act
together, and that in such a conjunction, as if they were one united
body; for it is, in my opinion, more probable, that one material
should act upon another material, or one immaterial upon another
immaterial, then that an immaterial should act upon a material or
corporeal. Thus the consideration or contemplation of immaterial
natural Spirits puts me always into doubts, and raises so many
contradictions in my sense and reason, as I know not, nor am not
able to reconcile them: However, though I am doubtful of them, yet
I can assure your self that I continue,
Madam,
Your Faithful Friend
and Servant.
[1] Of the Immortality of the Soul, l. 2. c. 10.

XXVI.
MADAM,
By reason the Soul is a Spirit, and therefore Contractible and
Dilatable, your Authors opinion is,[1] That it begins within less
compass at first in organising the fitly prepared matter, and so bears
it self on in the same tenour of work, till the body hath attained its
full growth; and that the Soul dilates it self in the dilating of the
Body, and so possesses it through all the members thereof. Truly,
Madam, as for the contraction and dilation of an immaterial Spirit, if
I heard never so many arguments, I should hardly be able to
conceive the possibility of it; For in my opinion, dilating and
contracting are motions and actions of Nature, which belong to
natural material Creatures, and to none else; for dilation and
contraction cannot be without extension, but extension belongs to
parts which an immaterial Spirit hath not: But suppose it be so, then
the Soul must contract and dilate, extend and shrink together, and
so grow less and bigger, according to the extension of the body; and
when the body dies, the soul, in my opinion, must contract to a very
point; and if one part of the body die before the other, the soul must
by degrees withdraw out of those parts: also when a part of the
body is cut off, the soul must needs contract, and grow less; the like
when a man is let blood. Which contracting of the soul, by your
Authors leave, doth seem, to my imagination, just like the
contracting of Hodmandod into her shell. Besides, if the soul be
individable, and equally spread all over the body, then, to my
opinion, she must necessarily be of a human shape; and if the body
be deformed, the soul must be deformed also; and if the body be
casually extended, as by taking Poyson into the body, the soul must
be so too, as being individable and filling every part; and if a man be
born with six fingers or toes, the soul must be so too; or if a dwarf,
the soul must be a dwarf also; and if he be born deaf and dumb, the
soul must be so too. But if two Twins, as it may fall out, should be
born united in one body, I would fain know then, whether they
would have two souls, or but one? As for example, if they should
have but one body, and one stomack, liver, heart, spleen, lungs,
bowels, and yet have four legs, four hands, and two heads: It
seems, to my opinion, that then two Immaterial Souls must be
joyned as into one; neither do I know yet how this could well be, the
monster having but one body, nor how that Immaterial Soul can be
divided, being inseparably double, when the body dies. But, Madam,
all this I speak of the Natural Soul of Man, not of the Divine Soul,
which is not subject to natural imperfections, and corporeal errors,
being not made by Nature, but a supernatural and divine gift of the
Omnipotent God, who surely will not give any thing that is not
perfect. Wherefore it is not probable, this Divine Soul, being not
subject to Nature, should be an architect of the body, as having an
higher and more divine imployment, viz. to fix her self on her
Creator, and being indued with supernatural faculties, and residing in
the body in a supernatural manner; all which I leave to the Church:
for I should be loth to affirm any thing contrary to their Doctrine, or
the Information of the holy Scripture, as grounding my belief onely
upon the sacred Word of God, and its true Interpretation made by
the Orthodox Church; but not upon the opinions of particular
persons: for particular mens opinions are not authentical, being so
different and various, as a man would be puzled which to adhere to.
Thus, Madam, I avoid, as much as ever I can, not to mix Divinity
with Natural Philosophy; for I consider, that such a mixture would
breed more confusion in the Church, then do any good to either;
witness the doctrine of the Soul of Man, whereof are so many
different opinions: The onely cause, in my opinion, is, that men do
not conceive the difference between the Divine, and Natural material
Soul of Man, making them both as one, and mixing or confounding
their faculties and proprieties, which yet are quite different; thus
they make a Hodg-podg, Bisk or Olio of both; proving Divinity by
Nature, and Faith by Reason; and bringing Arguments for Articles of
Faith, and sacred Mysteries out of Natural Arts and Sciences;
whereas yet Faith and Reason are two contrary things, and cannot
consist together; according to the Proverb, Where Reason ends,
Faith begins. Neither is it possible that Divinity can be proved by
Mathematical Demonstrations; for if Nature be not able to do it,
much less is Art: Wherefore it is inconvenient to mix supernatural
Spirits with Air, Fire, Light, Heat, Cold, &c. and to apply corporeal
actions and qualities to them; and the Divine Soul, with the Brain,
Blood, Flesh, Animal Spirits, Muscles, Nerves, Bones, &c. of Man; all
which makes a confusion betwixt the Mind or Natural Soul of Man,
and the Supernatural and Divine Soul inspired into him by God; for
both their faculties and proprieties are different, and so are their
effects, as proceeding from so different causes. And therefore,
Madam, as for Divinity, I pray devoutly, and believe without
disputing; but as for Natural Philosophy, I reason freely, and argue
without believing, or adhering to any ones particular opinion, which I
think is the best and safest way to choose for,
Madam,
Your faithful Friend,
and Servant.
[1] Of the Immortality of the Soul, l. 2. c. 10.

XXVII.
MADAM,
Your Author in the continuation of his discourse concerning the
Immaterial Soul of Man, demonstrating, that her seat is not bound
up in a certain place of the body, but that she pervades all the body
and every part thereof, takes, amongst the rest, an argument from
Passions and Sympathies: Moreover, says he,[1] Passions and
Sympathies, in my judgment, are more easily to be resolved into this
hypothesis of the Soul's pervading the whole Body, then in
restraining its essential presence to one part thereof.—But it is
evident that they arise in us against both our will and appetite; For
who would bear the tortures of fears and jelousies, if he could avoid
it? Concerning Passions, Madam, I have given my opinion at large in
my Book of Philosophy, and am of your Authors mind, that Passions
are made in the Heart, but not by an Immaterial spirit, but by the
Rational soul which is material; and there is no doubt, but that many
Passions, as Fear, Jealousie &c. arise against our will and appetite;
for so may forreign Nations invade any Kingdom without the will or
desire of the Inhabitants, and yet they are corporeal men: The same
may be said of Passions; and several parts of matter may invade
each other, whereof one may be afraid of the other, yet all this is but
according as corporeal matter moves, either Generally, or
Particularly: Generally, that is, when many parts of Matter unite or
joyn together, having the like appetites, wills, designs; as we may
observe, that there are general agreements amongst several parts,
in Plagues, as well as Wars, which Plagues are not onely amongst
Men, but amongst Beasts; and sometimes but in one sort of animals,
as a general Rot amongst Sheep, a general Mange amongst Dogs, a
general Farcy amongst Horses, a general Plague amongst Men; all
which could not be without a general Infection, one part infecting
another, or rather one part imitating the motions of the other, that is
next adjoyning to it; for such infections come by the neer adhesion
of parts, as is observable, which immaterial and individable natural
Spirits could not effect; that is, to make such a general infection in
so many several parts of so many several Creatures, to the
Creatures dissolution: Also there will be several Invasions at one
time, as Plague, and War, amongst neighbouring and adjoining
Creatures or Parts. But this is to be observed, That the sensitive
corporeal motions make all diseases, and not the Rational, although
the Rational are many times the occasion, that the sensitive do move
into such or such a disease; for all those that are sick by conceit,
their sicknesses are caused by the rational corporeal motions. But
being loth to make tedious repetitions hereof, having discoursed of
diseases, and passions in my mentioned Book of Philosophy, I will
refer you thither, and rest,
Madam,
Your Faithful Friend
and Servant.
[1] Immort. of the Soul. Book 2. c. 10
XXVIII.
MADAM,
Concerning Dimness of Sight, which your Author will have to
proceed from the deficiency of the Animal Spirits,[1] My meaning in
short is, That when sight is dim, though the sensitive organs are
perfect, this dimness is caused by the alteration onely of the
sensitive motions in the organs, not moving to the nature of sight.
And so is made Deafness, Dumbness, Lameness, and the like, as
also Weariness; for the Relaxation of strength in several parts, is
onely an alteration of such sorts of motions which make the nerves
strong; and if a man be more dull at one time, then at another, it is
that there are not so many changes of motions, nor so quick
motions at that time, as at another; for Nature may use more or less
force as she pleases: Also she can and doth often use opposite
actions, and often sympathetical and agreeable actions, as she
pleases; for Nature having a free power to move, may move as she
will; but being wise, she moves as she thinks best, either in her
separating or uniting motions, for continuance, as well as for variety.
But if, according to your Author, the Immaterial Soul should
determinate matter in motion, it would, in my opinion, make a
confusion; for the motions of the Matter would often oppose and
cross the motions of the Immaterial Soul, and so they would
disagree, as a King and his Subjects, (except God had given the Soul
an absolute power of command, and restrained matter to an
irrisistible and necessitated obedience; which, in my opinion, is not
probable:) By which disagreement, Nature, and all that is in Nature,
would have been quite ruined at this time; for no kinds, sorts, or
particulars, would keep any distinction, if Matter did not govern it
self, and if all the parts did not know their own affairs, abilities,
offices, and functions: Besides, it would, to my thinking, take up a
great deal of time, to receive commands in every several action, at
least so much, that for example, a man could not have so many
several thoughts in so short a time, as he hath. But concerning the
Animal Spirits, which your Author calls the Instruments, Organs and
Engines of the Incorporeal Soul; I would fain know, whether they
have no motion but what comes from the Soul, or whether they
have their own motion of themselves? If the first, then the Soul
must, in my opinion, be like a Deity, and have a divine Power, to give
and impart Motion; if the second, then the spirits being material, it
follows that Matter hath motion of it self, or is self-moving; But if the
Immaterial natural Soul can transfer her gifts upon corporeal matter,
then it must give numerous sorts of motions, with all their degrees;
as also the faculty of figuring, or moving figuratively in all corporeal
Matter: Which power, in my judgment, is too much for a Creature to
give. If you say, the Immaterial Soul hath this power from God; I
answer, Matter may have the same; and I cannot imagine why God
should make an Immaterial Spirit to be the Proxy or Vice-gerent of
his Power, or the Quarter-master General of his Divine Providence,
as your Author is pleased to style it,[2] when he is able to effect it
without any Under-Officers, and in a more easie and compendious
way, as to impart immediately such self-moving power to Natural
Matter, which man attributes to an Incorporeal Spirit. But to
conclude, if the Animal Spirits be the Instruments of the Incorporeal
Soul, then the Spirits of Wine are more powerful then the Animal
Spirits, nay, then the Immaterial Soul her self; for they can put them
and all their actions quite out of order: the same may be done by
other material things, Vegetables, Minerals, and the like. And so
leaving this discourse to your better consideration, I take my leave
for this time, and rest,
Madam,
Your faithful and affectionate Friend,
and Servant.
[1] Immort. of the Soul. Book 2. ch. 8.
[2] Immort. of the Soul. Book 3. c. 13.
XXIX.
MADAM,
Touching the State or Condition of the Supernatural and Divine Soul,
both in, and after this life, I must crave your excuse that I can give
no account of it; for I dare affirm nothing; not onely that I am no
professed Divine, and think it unfit to take any thing upon me that
belongs not to me, but also that I am unwilling to mingle Divinity
and Natural Philosophy together, to the great disadvantage and
prejudice of either; for if each one did contain himself within the
circle of his own Profession, and no body did pretend to be a Divine
Philosopher, many absurdities, confusions, contentions, and the like,
would be avoided, which now disturb both Church and Schools, and
will in time cause their utter ruine and destruction; For what is
Supernatural, cannot naturally be known by any natural Creature;
neither can any supernatural Creature, but the Infinite and Eternal
God, know thorowly everything that is in Nature, she being the
Infinite servant of the Infinite God, whom no finite Creature, of what
degree soever, whether natural or supernatural, can conceive; for if
no Angel nor Devil can know our thoughts, much less will they know
Infinite Nature; nay, one finite supernatural Creature cannot, in my
opinion, know perfectly another supernatural Creature, but God
alone, who is all-knowing; And therefore all what is said of
supernatural Spirits, I believe, so far as the Scripture makes mention
of them; further I dare not presume to go; the like of the
supernatural or divine Soul: for all that I have writ hitherto to you of
the Soul, concerns the natural Soul of Man, which is material, and
not the supernatural or divine Soul; neither do I contradict any thing
concerning this divine soul, but I am onely against those opinions,
which make the natural soul of man an immaterial natural spirit, and
confound supernatural Creatures with natural, believing those spirits
to be as well natural Creatures and parts of Nature, as material and
corporeal beings are; when as there is great difference betwixt
them, and nothing in Nature to be found, but what is corporeal.
Upon this account I take all their relations of Dæmons, of the Genii,
and of the Souls after the departure from humane Bodies, their
Vehicles, Shapes, Habitations, Converses, Conferences,
Entertainments, Exercises, Pleasures, Pastimes, Governments,
Orders, Laws, Magistrates, Officers, Executioners, Punishments, and
the like, rather for Poetical Fictions, then Rational Probabilities;
containing more Fancy, then Truth and Reason, whether they
concern the divine or natural Soul: for as for the divine Soul, the
Scripture makes no other mention of it, but that immediately after
her departure out of this natural life, she goeth either to Heaven or
Hell, either to enjoy Reward, or to suffer Punishment, according to
man's actions in this life. But as for the Natural Soul, she being
material, has no need of any Vehicles, neither is natural death any
thing else but an alteration of the rational and sensitive motions,
which from the dissolution of one figure go to the formation or
production of another. Thus the natural soul is not like a Traveller,
going out of one body into another, neither is air her lodging; for
certainly, if the natural humane soul should travel through the airy
regions, she would at last grow weary, it being so great a journey,
except she did meet with the soul of a Horse, and so ease her self
with riding on Horse-back. Neither can I believe Souls or Dæmons in
the Air have any Common-wealth, Magistrates, Officers and
Executioners in their airy Kingdom; for wheresoever are
Governments, Magistrates and Executioners, there are also Offences,
and where there is power to offend, as well as to obey, there may
and will be sometimes Rebellions and Civil Wars; for there being
different sorts of Spirits, it is impossible they should all so well
agree, especially the good and evil Genii, which certainly will fight
more valiantly then Hector and Achilles, nay, the Spirits of one sort
would have more Civil Wars then ever the Romans had; and if the
Soul of Cæsar and Pompey should meet, there would be a cruel fight
between those two Heroical souls; the like between Augustus's and
Antonius's Soul. But, Madam, all these, as I said, I take for fancies
proceeding from the Religion of the Gentiles, not fit for Christians to
embrace for any truth; for if we should, we might at last, by avoiding
to be Atheists, become Pagans, and so leap out of the Frying-pan
into the Fire, as turning from Divine Faith to Poetical Fancy; and if
Ovid should revive again, he would, perhaps, be the chief head or
pillar of the Church. By this you may plainly see, Madam, that I am
no Platonick; for this opinion is dangerous, especially for married
Women, by reason the conversation of the Souls may be a great
temptation, and a means to bring Platonick Lovers to a neerer
acquaintance, not allowable by the Laws of Marriage, although by
the sympathy of the Souls. But I conclude, and desire you, not to
interpret amiss this my discourse, as if I had been too invective
against Poetical Fancies; for that I am a great lover of them, my
Poetical Works will witness; onely I think it not fit to bring Fancies
into Religion: Wherefore what I have writ now to you, is rather to
express my zeal for God and his true Worship, then to prejudice any
body; and if you be of that same Opinion, as above mentioned, I
wish my Letter may convert you, and so I should not account my
labour lost, but judg my self happy, that any good could proceed to
the advancement of your Soul, from,
Madam,
Your faithful Friend
and Servant.

XXX.
MADAM,
I sent you word in my last, I would not meddle with writing any
thing of the Divine Soul of Man, by reason it belongs to Faith and
Religion, and not to Natural Philosophy; but since you desire my
opinion concerning the Immortality of the Divine Soul, I cannot but
answer you plainly, that first I did wonder much you made question
of that, whose truth, in my opinion, is so clear, as hardly any rational
man will make a doubt of it; for I think there is almost no Christian
in the world, but believes the Immortality of the Soul, no not
Christians onely, but Mahometans and Jews: But I left to wonder at
you, when I saw Wise and Learned Men, and great Divines, take so
much pains as to write whole volumes, and bring so many
arguments to prove the Immortality of the Soul; for this was a
greater Miracle to me, then if Nature had shewed me some of her
secret and hidden effects, or if I had seen an Immaterial Spirit.
Certainly, Madam, it seems as strange to me to prove the
Immortality of the Soul, as to convert Atheists; for it [is] impossible,
almost, that any Atheist should be found in the World: For what Man
would be so senceless as to deny a God? Wherefore to prove either
a God, or the Immortality of the Soul, is to make a man doubt of
either: for as Physicians and Surgeons apply strengthening
Medicines onely to those parts of the body which they suppose the
weakest, so it is with proofs and arguments, those being for the
most part used in such subjects, the truth of which is most
questionable. But in things Divine, Disputes do rather weaken Faith,
then prove Truth, and breed several strange opinions; for Man being
naturally ambitious, and endeavouring to excel each other, will not
content himself with what God has been pleased to reveal in his holy
Word; but invents and adds something of his own; and hence arise
so many monstrous expressions and opinions, that a simple man is
puzzled, not knowing which to adhere to; which is the cause of so
many schismes, sects, and divisions in Religion: Hence it comes also,
that some pretend to know the very nature and essence of God, his
divine Counsels, all his Actions, Designs, Rules, Decrees, Power,
Attributes, nay, his Motions, Affections, and Passions, as if the
Omnipotent Infinite God were of a humane shape; so that there are
already more divisions then Religions, which disturb the peace and
quiet both of mind and body; when as the ground of our belief
consists but in some few and short Articles, which clearly explained,
and the moral part of Divinity well pressed upon the People, would
do more good, then unnecessary and tedious disputes, which rather
confound Religion, then advance it: but if man had a mind to shew
Learning, and exercise his Wit, certainly there are other subjects,
wherein he can do it with more profit, and less danger, then by
proving Christian Religion by Natural Philosophy, which is the way to
destroy them both. I could wish, Madam, that every one would but
observe the Command of Christ, and give to God what is Gods, and
to Cæsar what is Cæsars, and so distinguish what belongs to the
actions of Nature, and what to the actions of Religion; for it appears
to my Reason, that God hath given Nature, his eternal Servant, a
peculiar freedom of working and acting, as a self-moving Power from
Eternity; but when the Omnipotent God acts, he acts supernaturally,
as beyond Nature; of which divine actions none but the holy Church,
as one united body, mind and soul, should discourse, and declare
the truth of them, according to the Revelation made by God in his
holy Word, to her Flock the Laity, not suffering any one single
person, of what profession or degree soever, indifferently to
comment, interpret, explain, and declare the meaning or sense of
the Scripture after his own fancy. And as for Nature's actions, let
those whom Nature hath indued with such a proportion of Reason,
as is able to search into the hidden causes of natural effects,
contemplate freely, without any restraint or confinement; for Nature
acts freely, and so may natural Creatures, and amongst the rest
Man, in things which are purely natural; but as for things
supernatural, man cannot act freely, by reason they are beyond his
sphere of conception and understanding, so as he is forced to set
aside Reason, and onely to work by Faith. And thus, Madam, you see
the cause why I cannot give you a full description of the Divine Soul
of Man, as I mentioned already in my last, but that I do onely send
you my opinion of the natural soul, which I call the rational soul; not
that I dare say, the supernatural soul is without natural reason, but
natural reason is not the divine soul; neither can natural reason,
without Faith, advance the divine soul to Heaven, or beget a pious
zeal, without divine and supernatural Grace: Wherefore Reason, or
the rational Soul is onely the Soul of Nature, which being material, is
dividable, and so becomes numerous in particular natural Creatures;
like as the sensitive life being also material and dividable, becomes
numerous, as being in every Creature, and in every part of every
Creature; for as there is life in every Creature, so there is also a soul
in every Creature; nay, not onely in every Creature, but in every
particle of every Creature, by reason every Creature is made of
rational and sensitive Matter; and as all Creatures or parts of Nature
are but one infinite body of Nature, so all their particular souls and
lives make but one infinite soul and life of Nature; and this natural
soul hath onely natural actions, not supernatural; nor has the
supernatural soul natural actions; for although they subsist both
together in one body, yet each works without disturbance to the
other; and both are Immortal; for of the supernatural soul there is
no question, and of the natural soul, I have said before, that nothing
is perishable or subject to annihilation in nature, and so no death,
but what is called by the name of death, is onely an alteration of the
corporeal natural motions of such a figure to another figure; and
therefore as it is impossible, that one part of Matter should perish in
Nature, so is it impossible, that the natural or rational soul can
perish, being material: The natural humane soul may alter, so as not
to move in an animal way, or not to have animal motions, but this
doth not prove her destruction or annihilation, but onely a change of
the animal figure and its motions, all remaining still in Nature. Thus
my Faith of the Divine, and my opinion of the Natural Soul, is, that
they are both Immortal; as for the immediate actions of the Divine
Soul, I leave you to the Church, which are the Ministers of God, and
the faithful dispensers of the sacred mysteries of the Gospel, the
true Expounders of the Word of God, Reformers of mens lives, and
Tutors of the Ignorant, to whom I submit my self in all that belongs
to the salvation of my Soul, and the regulating of the actions of my
life, to the honour and glory of God. And I hope they will not take
any offence at the maintaining and publishing my opinions
concerning Nature and Natural effects, for they are as harmless, and
as little prejudicial to them, as my designs; for my onely and chief
design is, and ever hath been to understand Nature rightly, obey the
Church exactly, Believe undoubtedly, Pray zealously, Live vertuously,
and Wish earnestly, that both Church and Schools may increase and
flourish in the sacred knowledg of the true Word of God, and that
each one may live peaceable and happily in this world, die quietly,
and rise blessedly and gloriously to everlasting Life and happiness:
Which happiness I pray God also to confer upon your Ladiship; Till
then, I rest,
Madam,
Your faithful and constant
Friend, to serve you.

XXXI.
MADAM,
I will leave the Controversie of Free-Will and Necessity, which your
Author is discoursing of,[1] to Divines to decide it, onely I say this,
that Nature hath a natural Free-will and power of self-moving, and is
not necessitated; but yet that this Free-will proceeds from God, who
hath given her both will and power to act freely. But as for the
question, whether there be nothing in the Universe, but meer body?
[2] I answer, My opinion is not, that there is nothing in the world but
meer Body; but that Nature is purely material or corporeal, and that
there is no part of Nature, or natural Creature, which is not Matter,
or Body, or made of Matter; also, that there is not any thing else
mixt with body, as a copartner in natural actions, which is distinct
from Body or Matter; nevertheless, there may be supernatural
spiritual beings or substances in Nature, without any hinderance to
Matter or corporeal Nature. The same I may say of the natural
material, and the divine and supernatural Soul; for though the divine
Soul is in a natural body, and both their powers and actions be
different, yet they cause no ruine or disturbance to each other, but
do in many cases agree with each other, without incroachment upon
each others powers or actions; for God, as he is the God of all
things, so the God of Order. Wherefore it is not probable, that
created Immaterial or Incorporeal beings should order Corporeal
Nature, no more then Corporeal Nature orders Immaterial or
Incorporeal Creatures. Neither can, in my opinion, Incorporeal
Creatures be clearly conceived by Corporeals, although they may
really exist and subsist in Nature; onely, as I said before, it is well to
be considered, that there is difference betwixt being in Nature, and
being a part of Nature; for bodiless things, and so spiritual
substances, although they may exist in Nature, yet they are not
natural, nor parts of Nature, but supernatural, Nature being meerly
corporeal, and Matter the ground of Nature; and all that is not built
upon this material ground, is nothing in Nature. But you will say, The
divine Soul is a part of Man, and Man a part of Nature, wherefore
the divine Soul must needs be a part of Nature. I answer, Not: For
the divine Soul is not a part of Nature, but supernatural, as a
supernatural Gift from God onely to Man, and to no other Creature:
and although in this respect it may be called a part of Man, yet it is
no natural or material part of Man; neither doth this supernatural
Gift disturb Nature or natural Matter, or natural Matter this
supernatural Gift. And so leaving them both, I rest,
Madam,
Your faithful Friend
and Servant.
[1] Of the Immortality of the Soul. l. 1. c. 3.
[2] Lib. 2. c. 2.

XXXII.
MADAM,
If you desire my opinion concerning Witches, whereof your Learned
Author hath many Discourses and Stories:[1] I will tell you really,
that in my sense and reason, I do not believe any, except it be the
witch of Endor, which the Scripture makes mention of; for though I
believe that there is a Devil, as the Word of God and the Church
inform me, yet I am not of the opinion, that God should suffer him
to have such a familiar conjunction, and make such contracts with
Man, as to impower him to do mischief and hurt to others, or to
foretell things to come, and the like; for I believe that all things
Immaterial, as Spirits, Angels, Devils, and the divine Soul of Man,
are no parts of Nature, but Supernatural, Nature knowing of no
Creature that belongs to her, but what is material; and since
incorporeal Creatures are no parts of Nature, they neither have
natural actions, nor are they concerned as co-partners or co-agents
in the actions of Nature and natural Creatures; but as their
substances, so their actions are supernatural, and beyond our
conceivement. As for Faires, I will not say, but there may be such
Creatures in Nature, and have airy bodies, and be of a humane
shape, and have humane actions, as I have described in my Book of
Poems; for there are many things, in Nature, whereof Man hath no
knowledg at all, and it would be a great folly for any one to deny
what he doth not see, or to ascribe all the unusual effects in Nature
to Immaterial Spirits; for Nature is so full of variety, that she can and
doth present sometimes such figures to our exterior senses, as are
not familiar to us, so as we need not to take our refuge to
Immaterial Spirits: nay, even those that are so much for Incorporeal
Spirits, must confess, that they cannot be seen in their own natures,
as being Invisible, and therefore have need to take vehicles of some
grosser bodies to manifest themselves to men: and if Spirits cannot
appear without bodies, the neerest way is to ascribe such unusual
effects or apparitions, as happen sometimes, rather to matter that is
already corporeal, and not to go so far as to draw Immaterial Spirits
to Natural actions, and to make those Spirits take vehicles fit for
their purposes: for Nature takes sometimes delight in unusual
Varieties. Concerning those stories which your Author relates[2] of
the strange effects of Food received into a mans body, how they did
work upon the Imagination, and change and transform the humors
of those that did feed upon them, those, I say, seem very probable
to me. As for example; of a Wench who being struck into an
Epilepsy, upon the seeing of a Malefactors Head cut off, was advised
to drink Cats-blood; which being done, she not long after
degenerated into the nature and property of that Animal, cried and
jump'd like a Cat, and hunted Mice with the same silence and
watchfulness as they do. Then of a Man, being long fed with Swines-
blood, which took a special pleasure in wallowing and tumbling
himself in the mire. Also of a Girle, which being nourished up with
Goats-milk, would skip like a Goat, and brouze on Trees as Goats use
to do. And of a Man, who by eating the brains of a Bear, became of
a Bear-like disposition. All these stories I believe to be true; for
naturally the motions of a Man may sometimes Sympathize so much
with the received food, as to make an alteration in his humour or
disposition. But although it be natural, yet it is not regular, at least
not usual, but proceeds from an irregular and unusual change of
motions, like as the conception and generation of a Monster; For if it
were ordinary, then those which drink much of the blood of beasts,
would also degenerate into a beastly nature, the contrary whereof is
sufficiently known: Likewise those that drink much of Cows-milk,
would change into their humors and natures. But certainly, some
kinds of meats do not onely cause sickness, but madness, and
strange Imaginations; all which unnatural or unusual accidents are
caused by Matter's irregular motions; Whereof I have declared my
opinion in other places; and so I rest,
Madam,
Your faithful and constant
Friend, to serve you.
[1] Antid. lib. 3.
[2] In his discourse of Enthusiasm.

XXXIII.
MADAM,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like