Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Beginning Spring Data: Data Access

and Persistence for Spring Framework


6 and Boot 3 Andres Sacco
Visit to download the full and correct content document:
https://ebookmass.com/product/beginning-spring-data-data-access-and-persistence-f
or-spring-framework-6-and-boot-3-andres-sacco/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

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


Another random document with
no related content on Scribd:
manner of disease and misfortune upon themselves if they
omitted to observe the ancestral rites.
“In the matter of sacrifice, relationship, even though distant,
is of significance, legitimate or illegitimate relationship being
regarded without distinction. A sacrifice is offered by a family,
with its entire relationship, once in two years. Others, even
the inhabitants of other towns, are invited. Such sacrifices are
commonly held in autumn, rarely in winter. As their
connections are large, each Indian will have opportunity to
attend more than one family sacrifice a year. The head of the
family knows the time and he must provide for everything.
When the head of such a family is converted, he gets into
difficulty because his friends will not give him peace until he
has designated some one to take his place in the
arrangement of sacrificial feasts.
“Preparations for such a sacrificial feast extend through
several days. The requisite number of deer and bears is
calculated and the young people are sent into the woods to
procure them together with the leader whose care it is to see
that everything needful is provided. These hunters do not
return until they have secured the amount of booty counted
upon. On their return they fire a volley when near the town,
march in in solemn procession and deposit the flesh in the
house of sacrifice. Meantime the house has been cleared and
prepared. The women have prepared firewood and brought in
long dry reed grass, which has been strewn the entire length
of the house, on both sides, for the guests to sit upon. Such a
feast may continue for three or four nights, the separate
sessions beginning in the afternoon and lasting until the next
morning. Great kettles full of meat are boiled and bread is
baked. These are served to the guests by four servants
especially appointed for this service. The rule is that whatever
is thus brought as a sacrifice must be eaten altogether and
nothing left. A small quantity of melted fat only is poured into
the fire. The bones are burnt, so that the dogs may not get
any of them. After the meal the men and women dance, every
rule of decency being observed. It is not a dance for pleasure
or exercise, as is the ordinary dance engaged in by the
Indians. One singer only performs during the dance, walking
up and down, rattling a small tortoise shell filled with pebbles.
He sings of the dreams the Indians have had, naming all the
animals, elements and plants they hold to be spirits. None of
the spirits of things that are useful to the Indians may be
omitted. By worshipping all the spirits named they consider
themselves to be worshipping God, who has revealed his will
to them in dreams. When the first singer has finished he is
followed by another. Between dances the guests may stop to
eat again. There are four or five kinds of feasts, the
ceremonies of which differ much from one another.
“At these feasts there are never less than four servants, to
each of whom a fathom of wampum is given that they may
care for all necessary things. During the three or four days
they have enough to do by day and by night. They have
leave, also, to secure the best of provisions, such as sugar,
bilberries, molasses, eggs, butter and to sell these things at a
profit to guests and spectators.”

Adams’ Account.—The best and, in fact, the only late account


previous to his own first article[47] the writer has seen of the Annual
Ceremony among the Lenape in Oklahoma, is that written by
Adams,[48] which reads as follows:

“The peculiar steps which they use in this dance have


caused the name ‘stomp’ or ‘stamp’ to be applied to it.
“In regard to the stomp dances of our people, we have
several kinds of dances; the most important one is the
‘worship dance’ which is carried on in a large building called a
temple, which is rectangular and ranges from 60 to 80 feet
long, from 30 to 40 feet wide, and is about 10 feet high. It is
built of wood with 2 doors. The main entrance is at the
eastern door, and it has only a dirt floor.
“On each post is carved a human face. On the center post
or one in the center of the building four faces are carved;
each face is painted one-half red and one-half black. All the
people enter at the east and go out the same way. When they
come in they pass to the right of the fire, and each of the
three clans of the Delawares take seats next to the wall, the
Turtle clan on the south, the Turkey on the west, and the Wolf
on the north. In no case can any one pass between the center
post and east door, but must go around the center post, even
to go to the north side of the temple.
“This dance is held once each year, in the fall, and
generally in October, in the full moon, and lasts not less than
12 days for each part. The tribe is divided into three clans,
and each clan has to go through the same part, so the dance
is sometimes 36 days long, but sometimes the second and
third clans do not dance more than 6 days each.
“The Turtle clan usually lead or begin the dance. A tortoise
shell, dried and beautifully polished and containing several
small pebbles, is placed in the southeast corner near the door
in front of the first person. If he has anything to say he takes
the shell and rattles it, and an answer comes from the south
side of the temple from the singers, who strike on a dried
deer’s hide: then the party who has the tortoise shell makes
an address or talk to the people, and thanks the Great Spirit
for blessings, and then proceeds to dance, going to the right
and around the fire, followed by all who wish to take part, and
finally coming to the center post he stops there; then all the
dancers shake hands and return to their seats. Then the shell
is passed to the next person, who dances or passes it on, as
he chooses.
“On the third day of the dance all men, both married and
single, are required to keep out of the company of women for
3 days at least. They have a doorkeeper, a leader, and 2 or 3
parties who sweep the ground floor with turkey wings, and
who also serve as deacons. The ashes from the fire are
always taken out at the west door, and the dirt is always
swept in the fire. In front of the east door outside is a high
pole on which venison hangs. It is a feast dance and the
deacons distribute food among the people. The officers and
waiters are paid in wampum for their services.
“In no case is a dog allowed to enter the temple, and no
one is allowed to laugh inside it, or in any way be rude. Each
person is allowed to speak and tell his dream or dreams or to
give advice. It is believed by the Delawares that every one
has a guardian spirit which comes in the form of some bird,
animal, or other thing, at times in dreams, and tells them what
to do and what will happen. The guardian spirit is sent from
the Great Spirit.
“Traditions say that 10 years before white men came to this
country (America) a young man told his dream in the temple.
This was on the Atlantic coast. He saw coming across the
great waters a large canoe with pinions (wings) and
containing strange people, and that in 10 years they would in
fact come. He told this dream and predicted the arrival of the
white men each year until they came and were seen by his
people. Many of our people still keep up this dance, but the
temple is not so large as it used to be, and the attendance
now is not more than 100 persons. Any Indian of any tribe can
also take part in the dance, but no white man can.
“When the dance is over all the people go out and stand in
a single line from east to west with their faces to the south.
Then they kneel down and pray, and then go home. We do
not know the origin of the worship dance, but the old Indians
claim that the Great Spirit came many years ago and
instructed it and also gave them the wampum.”

In spite of several inaccuracies, such as the statement that the


people face south (instead of east) while praying after the ceremony,
this account is valuable on account of the additional data it furnishes
on several points of interest, especially the tradition concerning the
prophecy of the coming of the whites.
Another Form of the Annual Ceremony
It appears that in former years there was, in addition to the rite just
described, another form of the Annual Ceremony practised by the
Lenape, before their removal to what is now Oklahoma from Kansas,
where the last man to “bring in” such a meeting was John Sarcoxie,
now dead.
The ceremony, which was called Muxhatolʹzing, seems, from the
accounts given the writer by his informants, to have taken place in a
similar building, and to have been similar in ritual to that just
described, except that it was held for only eight days instead of
twelve, and that, after the return of the hunters the skin of one of the
deer they had brought in was stuffed with grass and stood up by the
central post of the Big House, antlers and all, while about its neck
hung a string of wampum—perhaps as a propitiatory offering.
Moreover on the morning of the last day of the ceremony a large
sweathouse was built and stones heated; then about noon the men
who had been reciting their visions went into it, each taking one of
the hot stones with him. This privilege was not confined to the actual
celebrants however, for every one blessed by a guardian spirit even
if they had not sung their visions in the meeting, was entitled to carry
in a stone and join them.
The entrance was then closed and water poured upon the stones;
and while the steam rose and the sweathouse grew hotter and hotter
the perspiring occupants prayed to their guardian spirits and recited
their visions. These finished, with a shout of “There go our prayers to
Those Above,” the cover was suddenly snatched from the
sweathouse so that the steam it had contained rose in a puff. If the
steam cloud went straight up into the air it was thought that the
prayers would be heard and answered, and that all was well, but if it
broke and spread out the people felt that something had gone
wrong, and that their prayers were of no avail.
In endeavoring to explain the presence of such variations of the
Annual Ceremony, it should be remembered that the Lenape now in
Oklahoma whom the writer has called for convenience “Unami,” are
not really pure descendants of this tribe, but probably have a large
proportion of the blood of the Unala'ʹtko or Unalachtigo, whose
dialect, according to Heckewelder, was very similar, and a smaller
proportion of Minsi and even Nanticoke blood. Perhaps then the first
form of Annual Ceremony described may have originally been purely
Unami, and the second Unalachtigo, or Minsi, or vice versa; but later,
when the remnants of these tribes became amalgamated their mixed
descendants inherited both forms.
The second form seems to be a variant of the rite mentioned by
Zeisberger[49] who describes it as follows:

“A fifth kind of festival is held in honor of fire which the


Indians regard as being their grandfather, and call Machtuzin,
meaning ‘to perspire.’ A sweating-oven is built in the midst of
the house of sacrifice, consisting of twelve poles each of a
different species of wood. These twelve poles represent
twelve Manittos, some of these being creatures, others plants.
These they run into the ground, tie together at the top,
bending them toward each other; these are covered entirely
with blankets, joined closely together, each person being very
ready to lend his blanket, so that the whole appears like a
baker’s oven, high enough nearly to admit a man standing
upright. After the meal of sacrifice, fire is made at the
entrance of the oven and twelve large stones, about the size
of human heads, are heated and placed in the oven. Then
twelve Indians creep into it and remain there as long as they
can bear the heat. While they are inside twelve pipes full of
tobacco are thrown, one after another, upon the hot stones,
which occasions a smoke almost powerful enough to
suffocate those confined inside. Some one may also walk
around the stones singing and offering tobacco, for tobacco is
offered to fire. Usually, when the twelve men emerge from the
oven, they fall down in a swoon. During this feast a whole
buckskin with the head and antlers is raised upon a pole,
head and antlers resting on the pole, before which the Indians
sing and pray. They deny that they pay any adoration to the
buck, declaring that God alone is worshipped through this
medium and is so worshipped at his will.”

That this is really the same ceremony is shown not only by the
details as related but by the native name of the rite, the Machtuzin of
Zeisberger corresponding with the Muxhatolʹzing of the present
writer.
CHAPTER VI
Minsi Big House Ceremonies
The following account of the great ceremonies of the Minsi, which
correspond to the annual ceremony of the Unami, was obtained from
Chief James Wolf, now deceased, and his nephew, Chief Nellis
Timothy.

MYTH OF ORIGIN
At first, it appears, the Indians did not know how to worship, so
Kĕ'tanĭtoʹwĕt, the Great Manĭʹto or God, now called Pa'ʹtŭmawas,
came down and told them what to do. After following his instructions,
they watched him when he ascended. He carried twelve sumach
sticks in his hand, and they could see them shine far up in the air.
Every now and then he dropped one, and when he dropped the
twelfth he disappeared, while they heard the heavens crack like
thunder behind him as he went in. After this the Lenape began to
hold these meetings according to the instructions he had given them.

NUMBER OF CEREMONIES
There were two of these ceremonies every year, both held in the
Minsi Big House (W'aʹtekan), which was quite similar to that of the
Unami. One of these, performed about June when the wild
strawberries were ripe, lasted only a single night; the other, early in
winter, covered twelve days and nights. This latter corresponds to
the Annual Ceremony of the Unami.
At the June ceremony fresh strawberries were made into a drink
for the people, which reminds one of the Iroquois Strawberry Dance,
or Dance of First Fruits, as it is sometimes called. Strawberries were
dried at this time to make a drink for the Winter Ceremony.

ARRANGEMENT OF THE BIG HOUSE

Fig. 14.—Drum of dried deerskin, Minsi type. E. T. Tefft collection,


American Museum of Natural History. (Length 16.7 in.)
Fig. 15.—a,
Drumstick, Minsi
type; b, Prayerstick.
E. T. Tefft collection,
American Museum
of Natural History.
(Length of a, 19 in.)
Like the Unami Big House, that of the Minsi had a large central
post bearing carved faces; but, unlike that of the Unami, there was a
second short post, near the central one, upon which was hung, for
each ceremony, a raw fresh deerskin with the head and horns at the
top. This feature, however, corresponds with the second form of the
Annual Ceremony noted among the Lenape in Oklahoma and also
recorded by Zeisberger in Pennsylvania. Near this central post the
singers sat, and beat with four carved sticks upon a dry deerhide
folded into a square, in lieu of a drum (fig. 14), differing from the
Unami form, which is a rolled dry deerskin upon which are tied
several slats of wood (fig. 8). The drumsticks are flat, resembling
those of the Unami, as each bears a face carved upon one side, but
differ from them in the form of the forked end, and in width. Some, it
is said, represented women, the breasts being indicated as among
the Unami, but this feature does not appear in the set collected by
the writer at Grand River reserve (fig. 15, a), which the Indians said
were representative of the Minsi type.
There were two poles laid along on each side from end to end of
the Big House to divide the dancing place in the center from the
sitting places on the side, which were covered with a special kind of
leaves. Along these poles twelve little sumach sticks (fig. 15, b),
peeled and painted, were laid for twelve people to hold in their
hands, and tap on the poles in time to the music. There were also
provided a turtle rattle, which was placed at the foot of the central
pole; a fire-drill which Nellis Timothy thinks was worked on the
“pump-drill” principle, like that of the Unami, and a lot of entirely new
and unused bowls and spoons of bark. Unlike the Unami custom,
both doors of the Big House were used, the people always going in
at the east door and coming out at the west, and here also (like the
Unami) the ashes were carried out. “The Sun and everything else
goes toward the west,” say the Minsi, in explanation, “even the dead
when they die.”

PRELIMINARIES
The first act remembered by the informants preparatory to holding
a meeting was to send to each man in the tribe who had been
blessed by a “vision of power,” a little stick which represented an
invitation to the ceremony, the time of which the messenger gave
out, before which date the people leaving their scattered homes
gathered and camped about the Big House. Meanwhile hunters were
sent out, appointed before, not during the meeting as among the
Unami, to bring in for the Winter Ceremony, if possible, exactly
twelve deer, which were cooked by four young men who served as
attendants in a small separate house, built for the purpose.
Fire.—The fire was made with a fire-drill by a group of old men for
use in the Big House, but, as among the Unami, none of it could be
taken outside during the ceremony.
Purification.—When the two fires had been built, but before the
crowd had gathered, the house was purified by the smoke of
hemlock boughs thrown on the flames, and by sweeping the floor
with turkey-wing fans, which cleared away both dirt and evil
influences.

OPENING OF THE CEREMONY


Chief’s Speech.—The next step was for the attendants to call in all
the people from their camps except the women in their menses who
were not allowed to enter. When all were seated, the speaker rose
and addressed those assembled in terms like the following:
“We are now gathered here, our house is purified and clean, and
Pa'ʹtŭmawas is with us, ready to hear our worship. We must thank
Him for all the things that we enjoy, for He made them every one.”
Then he proceeded to tell the people not to drink liquor, nor to do
anything wrong in the Big House or in the camp about it, and advised
them to be always honest and kind and hospitable. He held virtue as
something to be followed, at the same time condemning evil, every
vice that he could think of being mentioned.
The chief then gave thanks for everything he could remember,
from the heavenly bodies to the animals, trees, and herbs of the
earth, not forgetting corn, beans, and squashes; and prayer for
successful hunting and good health for all the people. At the summer
meeting he prayed for good crops also. When he had finished,
bear’s fat was thrown on the two fires, and the smoke rose and filled
the place with its odor.

CEREMONIAL DRINK
At this point it was customary to pass around a vessel of drink
made of crushed wild strawberries, from which each person present
swallowed about a spoonful, a drink made at the Summer Ceremony
of fresh fruit, but in winter necessarily of berries dried for the
purpose.

RECITAL OF VISIONS
The first man to relate his vision (my informant did not remember
whether he was the one who “brought in” the meeting or not) took up
the turtle rattle from its place at the foot of the post and began to
shake it rapidly, while the singers struck the drum of dry hide. He
then recited the story of his vision of power, still keeping the rattle
shaking, following this with his dance song, at the same time dancing
and rattling the turtleshell.
Any one who wished to dance was supposed to give wampum to
the vision-teller for the privilege. Some who were well off would give
him an entire string, others merely a few beads. These the vision-
teller would take, when he had quite a handful, to two officers who
sat in a corner of the building, whose duty it was to count the
wampum, after which it was kept by the chief or leader. Sometimes if
a poor person who had no wampum wished to dance, they would
give him some to pay the vision-teller.
A translated example of a Minsi vision chant and dance song has
already been given. When the dream-teller finished the first verse of
his dance song, he exclaimed, “E-ye-he-ye-ĕ!” whereupon the
singers took up the strain and sang the verse several times, for the
benefit of those who wished to dance, omitting, however, the final
exclamation, but those who had bought the privilege rose and
danced where they stood, instead of circling around, as among the
Unami. Each “set” ended with a whoop, “kwi!”.
When the vision-teller finished dancing, he went around the house
and shook hands with everyone; then the turtle rattle was passed to
another man who had been blessed with a vision, and so on, until all
those qualified, who wished to recite their visions, had done so.

OTHER FEATURES
The Prayer Cry.—From time to time during the night the prayer cry
“Ho-o-o!” was repeated twelve times, and the twelfth cry, they say,
was heard by the Great Manĭʹto.
Feast.—The people were accustomed to eat a light supper before
going into the meeting; then about midnight the four attendants
carried around baskets with boiled meat and corn bread, and in the
morning, before leaving the Big House, a regular feast of venison
was served in new bark bowls and eaten with new bark spoons
especially made for the purpose.
Final Address.—Before the meeting closed, the speaker again
addressed the people, telling them to do right, and prayed that the
hunters about to leave for the winter hunt might be successful, and
that all might live to meet again.

CONCLUSION OF RITES
In the morning after the ceremonies in the Big House were
finished, the people filed out through the west door, circled about the
building, and lined up, facing eastward, to the east of it. Then they
raised their hands and cried “Ho-o-o!” twelve times, and the twelfth
time, it is said, their cry reached Heaven.
In comparing this form of the Annual Ceremony with that of the
Oklahoma Lenape the most noticeable difference is that here no
masked impersonator of Mĭsinghâliʹkŭn was seen in or about the Big
House, the Masks among the Minsi, as with the Iroquois, constituting
a society with its own separate rites.

GRAND RIVER VERSION


Such was the version of the great ceremonies given the writer by
the Minsi of Munceytown, Ontario, which is similar to, but more
detailed in parts than, the account previously obtained from the
Delawares of Grand River reserve, published by the writer in the
American Anthropologist[50] which we will reproduce here. It will be
noticed that this description gives fuller information in some places
where the first is deficient; so that between this and the preceding
account, a good general idea of the Minsi form of the ceremony can
be reconstructed. It reads:
“In the old religious ceremonies of the Delawares at Grand River a
very peculiar drum was used, a dry skin folded in rectangular form
and beaten with four sticks, each bearing a tiny human head carved
in relief (fig. 15, a). I secured the set of four original sticks from
Michael Anthony (Na'nkŭmaʹoxa), and employed him to make me a
reproduction of the drum (fig. 14) as the original had been destroyed.
This he did, and in addition made six painted sticks (fig. 15, b) also
used in the ceremony. The description of how these articles were
used, pieced together from several Indian accounts, may prove of
interest here.
“It appears that the Delawares of Six Nations Reserve formerly
held what was known as a ‘General Thanksgiving’ ceremony called
in Lenape Gitctlaʹkan, twice a year, once in the spring and again in
the fall. At these times it was customary to meet in the Cayuga long-
house, borrowed for the occasion. At a certain point in the
proceedings (I shall not attempt a consecutive description from
hearsay testimony) a man stood up and recited, in a rythmical sing-
song tone, his dream—the vision of power seen by him in his youth.
Na'nkŭmaʹoxa remembered how one old man was accustomed to tell
about a duck, half black and half white, which had appeared to him.
Between the verses of the dream four musicians kneeling at the
drum (pw'awaheʹgŭn) began a plaintive song, beating time with the
carved sticks (pw'awaheʹgŭnŭk). As they sang, the reciter swayed
his body to and fro, while a group of dancers gathered on the floor
behind him danced with a sidewise step. Before the ceremony, poles
were laid lengthwise along both sides of the council house, and
against these, at intervals, three on a side, the painted sticks, called
mkäähiʹgŭn, were laid. If anyone in the crowd felt ‘especially happy’
he was privileged to strike with one of these sticks upon one of the
poles in time to the music. The carved heads on the drumsticks
meant that human beings were giving thanks; the lengthwise
painting of the sticks, half black and half red, implied that men and
women were together in thanksgiving, the black representing the
warriors, the red the women. The fork at the striking end of the sticks
was to give a sharper sound. The dyes for producing the colors were
made by boiling bark, the black being soft maple (sexiʹkiminsi), and
the red, red alder bark (witoʹ'pi).
“In another part of the same ceremony wampum was used in the
form of strings and bunches, both of which were represented in my
collection from the Delawares. At least thirteen of the strings were
used, each one made different by different combinations of the white
and purple beads. These thirteen, it is said, represented respectively
(1) Earth; (2) Plants; (3) Streams and Waters; (4) Corn, Beans, and
Vegetables; (5) Wild Birds and Beasts; (6) Winds; (7) Sun; (8) Moon;
(9) Sky; (10) Stars; (11) Thunder and Rain; (12) Spirits; and (13)
Great Spirit. At the ceremony these strings were laid upon a bench
before a speaker, who picked them up one by one as he made his
address, each string reminding him of one part of his speech. He
began, my informant told me, by explaining that the Great Spirit had
made all things—the earth, plants, streams, and waters—everything.
Having thus enumerated all the things represented by the wampum,
he proceeded to speak to each of the remaining twelve directly,
holding the appropriate string in his hand. Thus he gave thanks to
the Earth for the benefits it gives to man, and prayed that its
blessings might continue; then thanked in the same way the Plants,
the Streams and Waters, the Winds; the Corn, Beans, and
Vegetables—each one in turn. As he finished each string he handed
it to an attendant, who laid it aside. When his long speech or prayer
was finished, he announced, ‘We will now enjoy ourselves,’ and
selected a man to distribute little bunches of wampum, three beads
in each, which served as invitations to join in the dancing that
followed. These bunches were delivered only to a certain number of
those known to be ‘sober and honest’ among the crowd in the long-
house. If any person wishing to dance failed to get invitation
wampum, it was his privilege to ask for one of the bunches, which
was given him if he was considered qualified. The first man receiving
wampum arose first; then the others, until the dancers were all on
the floor. It is said that this dance, which sometimes lasted all night,
did not circle around like most of the Iroquois dances, but each
performer remained in about the same spot.
“I was told that in this dance a small rattle without a handle and
made of turtleshell was used, probably like the box-turtle rattle still
used in the annual Planting Dance by the Seneca and Cayuga.”

WAUBUNO’S VERSION
The only extended account in print, known to the writer, of the
great ceremonies of the Minsi, beside his own, quoted above, is that
furnished by John Wampum, known as Chief Waubuno,[51] which
reads as follows:

“They kept annual feasts:—... a feast of first fruits which


they do not permit themselves to taste until they have made
an offering of them to the manitu-oo-al, or gods; ... There is
one of the greatest sacrifice offerings of our forefathers every
six months for cleansing themselves from sin; they will have
twelve deers to be consumed in one day and night. At the
great feast of the offerings of the first fruits of the earth, which
feast the Delawares or Munceys hold annually, they brought a
little of all that they raised, such as Indian corn, or hweisk-
queem, potatoes, beans, pumpkins, squashes, together with
the deer. The Indian women were busily engaged in cooking
their provisions, previous to the commencement of their
exercises. They invited all strangers into a long pagan temple
prepared for such purposes, there is a door at each end—one
opening to the east, and one opening to the west. On
entering, they with all the Indians were seated on the ground
around two fires; in the center of the temple was a large post,
around which was suspended a number of deer skins, and
wampum is kept buried at the foot of this post. Near the post
sat two Indian singers, each with a large bundle of undressed
deer skins which served as drums. There were two young
men appointed to watch the doors and keep the fires burning,
the doors being closed. Each of the young men brought an
armful of hemlock boughs, which being thrown on the fires
smothered them and caused a great smoke. In order that the
smoke might fill every corner of the temple, each man waved
his blanket over the fire; this was done with the idea of
purifying the temple and driving out the evil spirits. After the
smoke had subsided, the master of ceremonies, an old chief,
rose and began to rattle a turtle shell he had in his hand. He
delivered a speech to the people telling them the object of the
meeting was to thank the great spirit for the growth and
ripening of the corn. When he finished his speech he began to
dance, sing and rattle the shell, the two singers joining in,
beating on their skins. When he took his seat he handed the
shell to the next person, who performed in the same way, thus
it went from one to the other all night. The purport of their
speeches was to recount the mercies of the Great Spirit to
them during the past year, and telling any remarkable dreams
that they had had. In the course of the night a number of them
went out the west door, making a wailing noise to the moon,
and came in again the east door. In the morning the meat and
soup were divided amongst the people.
“These feasts often lasted twelve days and twelve nights,
and the Indians call it nee-shaw-neechk-togho-quanoo-maun,
or ween-da-much-teen. No drinking or improper conduct is
allowed. The utmost solemnity prevails.”
CHAPTER VII
The Mĭsiʹngʷ' or Mask
The Minsi version of the myth explaining the origin of their great
ceremonies has been already related, but not that of the Unami, for
the latter, which concerns itself with the origin of the Unami rites as
now practised, is so intimately interwoven with the story of the
Mĭsiʹngʷ', or mask (fig. 1), that it was thought best to place it in the
chapter devoted to that curious being, with whose position in the
Lenape pantheon, recorded history, and activities in the Annual
Ceremony, we have already become acquainted.
The myth is therefore presented herewith, as related by Chief
Charley Elkhair, the Lenape master of ceremonies, with only such
additions as later questioning brought forth.

ORIGIN OF THE MASK, AND OF THE BIG HOUSE


This is the way the Lenape found out that there is a living
Mĭsinghâliʹkŭn above us. Many years ago, when the Delawares lived
in the East, there were three boys who were not treated very well.
Their relatives did not take care of them, and it seemed as if it made
no difference whether the children died or not. These boys were out
in the woods thinking about their troubles, when they saw the
Mĭsinghâliʹkŭn or Living Solid Face. He came and spoke to them,
and gave them strength so that nothing could hurt them again. To
one of these boys he said, “You come along with me and I will show
you the country I come from.” So he took the boy up in the air to the
place whence he came, which is rocky mountains above us,
reaching out from the north and extending toward the south. It is not
the place where people go when they die, for it is not very far from
this earth. A long time ago people could see this country of
Mĭsinghâliʹkŭn, but none can see it now.
While he was showing the boy his country, the Mĭsinghâliʹkŭn
promised him that he would become stout and strong, and would
have the power to get anything he wished. Then he brought the boy
back.
Afterward, when the boy grew up and went hunting, he used to
see the Mĭsinghâliʹkŭn riding a buck around among the other deer,
herding them together. Thus it happened that there were three men
in the tribe, who knew that there is a Mĭsinghâliʹkŭn, because they
had seen him with their own eyes.
The Delawares had always kept a Big House (xiʹngwikan) to
worship in, but in those days it was built entirely of bark and had no
faces of the Mĭsiʹngʷ' carved upon the posts as it has now. Here they
used to sing about their dreams (visions of power); but some time
after the three boys talked with the Mĭsinghâliʹkŭn, the people gave
up this worship, and for ten years had none. Then there came a
great earthquake, which lasted twelve months and gave great
trouble to the Lenape. It came because they had abandoned the
worship their fathers had taught them. In those times the tribe lived
in towns, not scattered about the country as they are now, and in one
of these towns a chief had a big bark house, and here the people
met to worship, hoping to stop the earthquake, while they were
building a new Big House. When it was finished, they began to
worship there, and sang and prayed all winter for relief. After spring
came, they were holding a meeting one night when they heard the
Mĭsinghâliʹkŭn making a noise, “Hoⁿ-hoⁿ-hoⁿ,” right east of the Big
House. The chief, who did not know what was making the noise,
called for somebody to go and see what it was. Then these three
men offered to go, because, as they said, they knew what was
making the noise and could find out what he wanted. So they went
out and found Mĭsinghâliʹkŭn, and asked him what he wanted. He
answered:
“Go back and tell the others to stop holding meetings and attend to
their crops. Do not meet again until fall, when I will come and live
with you, and help in the Big House. You must take wood and carve
a face (Mĭsiʹngʷ') just like mine, painted half black and half red, as
mine is, and I will put my power in it, so that it will do what you ask.

You might also like