0% found this document useful (0 votes)
8 views81 pages

(Ebook) Beginning Spring Data: Data Access and Persistence For Spring Framework 6 and Boot 3 by Andres Sacco ISBN 9781484287637, 1484287630

The document provides information about various ebooks related to Spring Framework and Spring Boot, including titles, authors, and ISBNs. It promotes instant digital downloads in multiple formats and includes links to purchase or access the ebooks. Additionally, it highlights the importance of persistence in application architecture and offers insights into Spring Data and related technologies.

Uploaded by

jianafykesfb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views81 pages

(Ebook) Beginning Spring Data: Data Access and Persistence For Spring Framework 6 and Boot 3 by Andres Sacco ISBN 9781484287637, 1484287630

The document provides information about various ebooks related to Spring Framework and Spring Boot, including titles, authors, and ISBNs. It promotes instant digital downloads in multiple formats and includes links to purchase or access the ebooks. Additionally, it highlights the importance of persistence in application architecture and offers insights into Spring Data and related technologies.

Uploaded by

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

Download the Full Ebook and Access More Features - ebooknice.

com

(Ebook) Beginning Spring Data: Data Access and


Persistence for Spring Framework 6 and Boot 3 by
Andres Sacco ISBN 9781484287637, 1484287630

https://ebooknice.com/product/beginning-spring-data-data-
access-and-persistence-for-spring-framework-6-and-
boot-3-47453786

OR CLICK HERE

DOWLOAD EBOOK

Download more ebook instantly today at https://ebooknice.com


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

Start reading on any device today!

(Ebook) Practical Spring LDAP: Using Enterprise Java-Based


LDAP in Spring Data and Spring Framework 6 by Balaji
Varanasi, Andres Sacco ISBN 9798868800023, 9798868800016,
8868800020, 8868800012
https://ebooknice.com/product/practical-spring-ldap-using-enterprise-
java-based-ldap-in-spring-data-and-spring-framework-6-54527846

ebooknice.com

(Ebook) Pro Spring Security: Securing Spring Framework 6


and Boot 3–based Java Applications, Third Edition by
Massimo Nardone, Carlo Scarioni ISBN 9798868800351,
8868800357
https://ebooknice.com/product/pro-spring-security-securing-spring-
framework-6-and-boot-3based-java-applications-third-edition-55066978

ebooknice.com

(Ebook) Spring Boot Persistence Best Practices: Optimize


Java Persistence Performance in Spring Boot Applications
by Anghel Leonard ISBN 9781484256268, 1484256263
https://ebooknice.com/product/spring-boot-persistence-best-practices-
optimize-java-persistence-performance-in-spring-boot-
applications-50194838
ebooknice.com

(Ebook) Spring Boot Persistence Best Practices: Optimize


Java Persistence Performance in Spring Boot Applications
by Anghel Leonard ISBN 9781484256251, 1484256255
https://ebooknice.com/product/spring-boot-persistence-best-practices-
optimize-java-persistence-performance-in-spring-boot-
applications-11359766
ebooknice.com
(Ebook) Spring Quick Reference Guide: A Pocket Handbook
for Spring Framework, Spring Boot, and More by Adam L.
Davis ISBN 9781484261439, 9781484261446, 1484261437,
1484261445
https://ebooknice.com/product/spring-quick-reference-guide-a-pocket-
handbook-for-spring-framework-spring-boot-and-more-22417500

ebooknice.com

(Ebook) Pro Spring MVC with WebFlux: Web Development in


Spring Framework 5 and Spring Boot 2 by Marten Deinum;
Iuliana Cosmina ISBN 9781484256657, 1484256654
https://ebooknice.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-25767182

ebooknice.com

(Ebook) Pro Spring MVC with WebFlux: Web Development in


Spring Framework 5 and Spring Boot 2 - Second Edition by
Marten Deinum; Iuliana Cosmina ISBN 9781484256657,
1484256654
https://ebooknice.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-second-
edition-24679968
ebooknice.com

(Ebook) Java Persistence with Spring Data and Hibernate


(MEAP V04) by C■t■lin Tudose ISBN 9781617299186,
1617299189
https://ebooknice.com/product/java-persistence-with-spring-data-and-
hibernate-meap-v04-37765964

ebooknice.com

(Ebook) Beginning Spring Boot 3 by Siva Prasad Reddy


Katamreddy, Sai Subramanyam Upadhyayula ISBN
9781484287910, 1484287916
https://ebooknice.com/product/beginning-spring-boot-3-47262940

ebooknice.com
Beginning Spring Data
Data Access and Persistence
for Spring Framework 6 and Boot 3

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

ISBN-13 (pbk): 978-1-4842-8763-7 ISBN-13 (electronic): 978-1-4842-8764-4


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

Copyright © 2023 by Andres Sacco


This work is subject to copyright. All rights are reserved 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.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Steve Anglin
Development Editor: Laura Berendson
Coordinating Editor: Jill Balzano
Copyeditor: Kim Burton
Cover designed by eStudioCalamar
Cover image by Mink Mingle on Unsplash (www.unsplash.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit
www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
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.
Printed on acid-free paper
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
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� xi

About the Technical Reviewer������������������������������������������������������������������������������� xiii


Acknowledgments���������������������������������������������������������������������������������������������������xv

Introduction�����������������������������������������������������������������������������������������������������������xvii

Part I: Introduction����������������������������������������������������������������������������������������� 1
Chapter 1: Application Architecture������������������������������������������������������������������������� 3
Why Persistence Is So Important�������������������������������������������������������������������������������������������������� 3
The History of Persistence������������������������������������������������������������������������������������������������������������ 4
JDBC���������������������������������������������������������������������������������������������������������������������������������������� 5
EJB���������������������������������������������������������������������������������������������������������������������������������������� 12
JPA���������������������������������������������������������������������������������������������������������������������������������������� 16
Spring Data���������������������������������������������������������������������������������������������������������������������������� 19
Object Mapping��������������������������������������������������������������������������������������������������������������������� 20
Repository Support��������������������������������������������������������������������������������������������������������������������� 22
Architectures Types��������������������������������������������������������������������������������������������������������������������� 24
Layers������������������������������������������������������������������������������������������������������������������������������������ 24
Hexagonal������������������������������������������������������������������������������������������������������������������������������ 26
Persistence Design Patterns������������������������������������������������������������������������������������������������������� 29
Data Access Object (DAO)������������������������������������������������������������������������������������������������������ 29
Repository Pattern����������������������������������������������������������������������������������������������������������������� 32
Data Transfer Object (DTO)���������������������������������������������������������������������������������������������������� 34
Specification Pattern������������������������������������������������������������������������������������������������������������� 35
Other Patterns����������������������������������������������������������������������������������������������������������������������� 36
Summary������������������������������������������������������������������������������������������������������������������������������������ 36

v
Table of Contents

Chapter 2: Spring Basics and Beyond�������������������������������������������������������������������� 37


Spring Basics������������������������������������������������������������������������������������������������������������������������������ 37
Spring Boot��������������������������������������������������������������������������������������������������������������������������������� 39
Basic Application Setup�������������������������������������������������������������������������������������������������������������� 40
Creating an API Using Spring Initialzr������������������������������������������������������������������������������������ 41
Creating an API in the IDE������������������������������������������������������������������������������������������������������ 45
How to Run the Application��������������������������������������������������������������������������������������������������� 47
Best Practices����������������������������������������������������������������������������������������������������������������������������� 57
Preventing Conflicts with the Dependencies������������������������������������������������������������������������� 57
Documenting the Endpoints�������������������������������������������������������������������������������������������������� 59
Logging All the Details����������������������������������������������������������������������������������������������������������� 59
Maintaining and Updating the Dependencies������������������������������������������������������������������������ 60
Summary������������������������������������������������������������������������������������������������������������������������������������ 60

Chapter 3: Spring Data and Different Types of Persistence������������������������������������ 61


What Is Spring Data?������������������������������������������������������������������������������������������������������������������ 61
How Does Spring Data Work?����������������������������������������������������������������������������������������������������� 64
Spring Data Code Example���������������������������������������������������������������������������������������������������� 64
Core Concepts����������������������������������������������������������������������������������������������������������������������� 70
Summary������������������������������������������������������������������������������������������������������������������������������� 84

Part II: SQL Persistence�������������������������������������������������������������������������������� 85


Chapter 4: Persistence and Domain Model������������������������������������������������������������� 87
JPA Configuration Using Annotations������������������������������������������������������������������������������������������ 87
Entity������������������������������������������������������������������������������������������������������������������������������������� 91
Types of Relationships��������������������������������������������������������������������������������������������������������� 107
Types of Inherence�������������������������������������������������������������������������������������������������������������� 120
Listening and Auditing Events��������������������������������������������������������������������������������������������� 132
Validating the Schema�������������������������������������������������������������������������������������������������������������� 135
Summary���������������������������������������������������������������������������������������������������������������������������������� 141

vi
Table of Contents

Chapter 5: Transaction Management�������������������������������������������������������������������� 143


What Is a Transaction?�������������������������������������������������������������������������������������������������������������� 145
What Is ACID?���������������������������������������������������������������������������������������������������������������������� 146
Isolation Problems��������������������������������������������������������������������������������������������������������������� 147
Isolation Levels�������������������������������������������������������������������������������������������������������������������� 150
Locking Types���������������������������������������������������������������������������������������������������������������������� 152
How Do These Concepts Work in Spring Data?������������������������������������������������������������������������� 152
Transactional Properties������������������������������������������������������������������������������������������������������ 155
Transaction Template����������������������������������������������������������������������������������������������������������� 158
Optimistic Locking��������������������������������������������������������������������������������������������������������������� 159
Summary���������������������������������������������������������������������������������������������������������������������������������� 162

Chapter 6: Versioning or Migrating Changes�������������������������������������������������������� 163


Versioning Changes in a Database�������������������������������������������������������������������������������������������� 163
Libraries That Implement Versioning����������������������������������������������������������������������������������� 166
Which Library Does the Versioning?������������������������������������������������������������������������������������ 170
Integrating Libraries in Spring Boot������������������������������������������������������������������������������������� 170
Best Practices���������������������������������������������������������������������������������������������������������������������� 178
Feature Flags���������������������������������������������������������������������������������������������������������������������������� 179
Implementing Feature Flags������������������������������������������������������������������������������������������������ 181
Best Practices���������������������������������������������������������������������������������������������������������������������� 185
Summary���������������������������������������������������������������������������������������������������������������������������������� 185

Part III: NoSQL Persistence������������������������������������������������������������������������� 187


Chapter 7: Redis: Key/Value Database����������������������������������������������������������������� 189
What Is Redis?�������������������������������������������������������������������������������������������������������������������������� 189
Spring Data Structures�������������������������������������������������������������������������������������������������������������� 193
Database and Connection Settings������������������������������������������������������������������������������������������� 195
Connecting with Primary/Secondary Nodes������������������������������������������������������������������������ 200
Object Mapping and Conversion����������������������������������������������������������������������������������������������� 203

vii
Table of Contents

Defining Custom Repositories��������������������������������������������������������������������������������������������������� 206


Queries by Example������������������������������������������������������������������������������������������������������������������ 209
Summary���������������������������������������������������������������������������������������������������������������������������������� 212

Chapter 8: MongoDB: Document Database����������������������������������������������������������� 213


What Is a Document Store?������������������������������������������������������������������������������������������������������ 213
Possible Uses Cases������������������������������������������������������������������������������������������������������������ 214
Implementations������������������������������������������������������������������������������������������������������������������ 215
What Is MongoDB?�������������������������������������������������������������������������������������������������������������������� 216
Introduction Spring Data Mongo����������������������������������������������������������������������������������������������� 219
Database and Connection Settings������������������������������������������������������������������������������������� 219
Access Using Repositories�������������������������������������������������������������������������������������������������� 224
Defining Queries������������������������������������������������������������������������������������������������������������������ 226
Using MongoTemplate with Custom Repositories��������������������������������������������������������������� 227
Summary���������������������������������������������������������������������������������������������������������������������������������� 230

Chapter 9: Neo4j: Graph Database������������������������������������������������������������������������ 231


What Is a Graph Database?������������������������������������������������������������������������������������������������������� 231
Possible Uses Cases������������������������������������������������������������������������������������������������������������ 232
Implementations������������������������������������������������������������������������������������������������������������������ 233
What Is Neo4j?�������������������������������������������������������������������������������������������������������������������������� 234
Introduction Spring Data Neo4j������������������������������������������������������������������������������������������������� 236
Database and Connection Settings������������������������������������������������������������������������������������� 236
Access Using Repositories�������������������������������������������������������������������������������������������������� 241
Summary���������������������������������������������������������������������������������������������������������������������������������� 247

Chapter 10: Cassandra: Wide-Column Database�������������������������������������������������� 249


What Is Cassandra?������������������������������������������������������������������������������������������������������������������ 249
Structure������������������������������������������������������������������������������������������������������������������������������ 252
Configuration���������������������������������������������������������������������������������������������������������������������������� 253
Database and Connection Settings������������������������������������������������������������������������������������� 253

viii
Table of Contents

Defining Custom Repositories��������������������������������������������������������������������������������������������� 260


Defining a TTL���������������������������������������������������������������������������������������������������������������������� 263
Summary���������������������������������������������������������������������������������������������������������������������������������� 264

Part IV: Advanced testing and best practices��������������������������������������������� 265


Chapter 11: Reactive Access�������������������������������������������������������������������������������� 267
What Is Reactive Access?��������������������������������������������������������������������������������������������������������� 268
Modifying Queries to Be Reactive��������������������������������������������������������������������������������������������� 269
Non-Relational Databases��������������������������������������������������������������������������������������������������� 270
Relational Databases����������������������������������������������������������������������������������������������������������� 272
Considerations�������������������������������������������������������������������������������������������������������������������������� 275
Summary���������������������������������������������������������������������������������������������������������������������������������� 275

Chapter 12: Unit and Integration Testing�������������������������������������������������������������� 277


Unit Testing with Mocks������������������������������������������������������������������������������������������������������������ 278
Integration Testing with a Database������������������������������������������������������������������������������������������ 281
Testcontainers��������������������������������������������������������������������������������������������������������������������� 281
Testcontainers vs. Embedded���������������������������������������������������������������������������������������������� 283
Using Testcontainers����������������������������������������������������������������������������������������������������������� 284
Multiple Integration Tests���������������������������������������������������������������������������������������������������� 293
Initialization Strategies�������������������������������������������������������������������������������������������������������� 294
Potential Problems�������������������������������������������������������������������������������������������������������������� 295
Summary���������������������������������������������������������������������������������������������������������������������������������� 298

Chapter 13: Detecting Performance Issues���������������������������������������������������������� 299


Low-Performance Problems����������������������������������������������������������������������������������������������������� 300
Detecting Problems������������������������������������������������������������������������������������������������������������������� 301
Analyzing Query Performance��������������������������������������������������������������������������������������������� 301
Analyzing Query Complexity������������������������������������������������������������������������������������������������ 305
Checking the Performance of an Endpoint�������������������������������������������������������������������������� 310
Summary���������������������������������������������������������������������������������������������������������������������������������� 323

ix
Table of Contents

Chapter 14: Best Practices����������������������������������������������������������������������������������� 325


Compressing Information���������������������������������������������������������������������������������������������������������� 325
Reducing Transferred Information�������������������������������������������������������������������������������������������� 332
Using Optional in Custom Queries��������������������������������������������������������������������������������������������� 332
Using Lazy in Relationships������������������������������������������������������������������������������������������������������ 332
Persisting Multiples Elements��������������������������������������������������������������������������������������������������� 333
Using Master/Slave or Replicas������������������������������������������������������������������������������������������������ 333
Using Cache to Reduce Access������������������������������������������������������������������������������������������������� 334
Summary���������������������������������������������������������������������������������������������������������������������������������� 340

Appendix A: Setting up Environment Tools����������������������������������������������������������� 341

Appendix B: Recommended and Alternative Tools����������������������������������������������� 349

Appendix C: Opening a Project����������������������������������������������������������������������������� 363

Appendix D: Install and Configure a Relational Database������������������������������������ 367

Appendix E: Installing and Configuring Non-Relational Databases���������������������� 383

Appendix F: Further Reading�������������������������������������������������������������������������������� 407

Index��������������������������������������������������������������������������������������������������������������������� 411

x
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.

xi
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.

xiii
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.

xv
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.

1
https://spring.io/

xvii
Introduction

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.

xviii
Introduction

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.

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/

xix
Introduction

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

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.html
12
https://www.docker.com/
13
https://docker-curriculum.com/
14
https://michaelhaar.dev/my-docker-compose-cheatsheet

xx
Introduction

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.

15
https://snyk.io/jvm-ecosystem-report-2021/

xxi
Introduction

• 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.

xxii
CHAPTER 1

Application Architecture
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.

3
© Andres Sacco 2023
A. Sacco, Beginning Spring Data, https://doi.org/10.1007/978-1-4842-8764-4_1
Chapter 1 Application Architecture

• 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.

Figure 1-1. History of persistence

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.

1
https://snyk.io/jvm-ecosystem-report-2021/

4
Chapter 1 Application Architecture

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.

Figure 1-2. Structure of 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.

5
Chapter 1 Application Architecture

• 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.

2
https://www.jcp.org/en/jsr/detail?id=221
3
https://www.jcp.org/en/jsr/detail?id=54

6
Chapter 1 Application Architecture

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

7
Chapter 1 Application Architecture

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.
8
Chapter 1 Application Architecture

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.

9
Chapter 1 Application Architecture

Figure 1-4. The structure of the catalog database

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;

10
Chapter 1 Application Architecture

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

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.

11
Chapter 1 Application Architecture

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

E JB
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.

4
https://javaee.github.io/glassfish/
5
https://www.wildfly.org/
6
https://www.eclipse.org/jetty/

12
Chapter 1 Application Architecture

Figure 1-5. Features that provide EJB

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.

7
https://jakarta.ee/about/working-group/

13
Chapter 1 Application Architecture

Table 1-3. List of EJB Versions with Their Characteristics


Year Version Characteristics

1998/ EJB 1.0 • Introduces support to use Entity Beans for persistent objects
1999 • Has a remote interface to access remotely, so in a way, EJB is portable
1999 EJB 1.1 • Introduces the deployment descriptor in an XML which replaces a class that
contains all the metadata
2001 EJB 2.08 • Introduces compatibility with CORBA and other Java APIs
• 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
2003 EJB 2.19 • Adds support to create web services using SOAP
• Introduces the possibility of having a timer service to have a cron to invoke
certain 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 3.010 • Appears the POJO (Plain Old Java Objects) as a replacement for the EJB Bean class
• 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
• JPA entities were decoupled from the EJB container to use independently
2009 EJB 3.111 • EJB Lite runs multiple components in the same VM as an EJB client
2013 EJB 3.212 • Autocloseable interfaces
• Adds more control over the transactionality of life-cycle interceptor methods.
2020 EJB 4.013 • Deprecation of the EJBContext.getEnvironment() method
• Removes methods relying on JAX-RPC
• Most packages in javax.ejb moved to jakarta.ejb

8
https://www.jcp.org/en/jsr/detail?id=19
9
https://www.jcp.org/en/jsr/detail?id=153
10
https://www.jcp.org/en/jsr/detail?id=220
11
https://www.jcp.org/en/jsr/detail?id=318
12
https://www.jcp.org/en/jsr/detail?id=345
13
https://jakarta.ee/specifications/enterprise-beans/4.0/

14
Chapter 1 Application Architecture

E JB 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.

14
https://docs.oracle.com/cd/B19306_01/server.102/b14257/jm_create.htm

15
Chapter 1 Application Architecture

Figure 1-6. EJB Components and how to interact with JPA

J PA
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.

15
https://www.jcp.org/en/jsr/detail?id=338

16
Chapter 1 Application Architecture

Figure 1-7. Example of the structure of layers using JPA

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.

16
https://hibernate.org/
17
https://www.eclipse.org/eclipselink/
18
https://openjpa.apache.org/
19
https://spring.io/projects/spring-data

17
Chapter 1 Application Architecture

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
}

18
Chapter 1 Application Architecture

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.

S
 pring 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 ElasticSearch20 and Couchbase,21 are not
covered in this book because they have a similar structure for saving information.

20
https://www.elastic.co/
21
https://www.couchbase.com/

19
Chapter 1 Application Architecture

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

20
Chapter 1 Application Architecture

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 @Document( @NodeEntitypublic


@Table(name = collection="currency) class Currency
"currency") public class Currency { {
public class Currency @Id @GraphId
{ private Long id; private Long id;
@Id @Field("decimal_places") private String
@GeneratedValue private String decimalPlaces;
(strategy = decimalPlaces; //Other
GenerationType. //Other attributes attributes and
SEQUENCE) and set/get set/get
private Long id; } }
@Column(name =
"decimal_places",
length = 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.

21
Chapter 1 Application Architecture

Table 1-5. Declaring Relationships Among Objects in a Database


JPA MongoDB Neo4j

@Entity @Document( @NodeEntity


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

22
Chapter 1 Application Architecture

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

23
Chapter 1 Application Architecture

A
 rchitectures 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.

L ayers
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.

22
https://www.archunit.org/

24
Chapter 1 Application Architecture

Figure 1-10. The basic structure of layers

25
Chapter 1 Application Architecture

B
 enefits
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.

D
 rawbacks
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.

H
 exagonal
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

23
https://alistair.cockburn.us/hexagonal-architecture/

26
Chapter 1 Application Architecture

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.

Figure 1-11. Hexagonal architecture with the most relevant layers

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

27
Chapter 1 Application Architecture

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.

28
Other documents randomly have
different content
The arquebusier shouldered his arquebuse, and turned out the guard; the
arms rattled on the pavement; the drum beat; and the whole palace of
Falkland was aroused like that of the sleeping beauty in the wood.

CHAPTER LI.

THE KING AND THE CARDINAL.


"Ne'er should be a vassal banished,
Without time to plead his cause;
Ne'er should king his people's rights
Trample on, or break the laws:
Ne'er should he his liegemen punish,
More than to their crimes is due;
Lest they rise into rebellion—
That day sorely would he rue."
Rodrigo of Bivar.

"His eminence the cardinal, may it please your majesty," said the little
Lord Claud, announcing the visitor. Setting down the lap-dog, King James
started from his seat, and, without any further preamble, the tall and stately
figure of Beaton approached him. James knelt for a moment to receive his
blessing, and then pressed his hand in silence.

The poor king looked paler, thinner, and sadder than when the cardinal
had seen him last in Holyrood, beside that grave over which a nation
mourned; but this did not prevent the perfect courtier from saying—

"I rejoice to see your majesty looking so well."

"It is not merely to flatter you have disturbed my sad retirement," said
James, with one of his old smiles; "but welcome heartily, Lord Cardinal; I
have longed to converse with you anent many things."

The little dog whined, and the king took it again in his hands to caress it,
while the page withdrew, and the cardinal seated himself. "Here are
splendour and magnificence," thought he, "saloons full of guards, and
chambers full of courtiers, pages, lacqueys, wealth, and rank—but where is
happiness?"

"My lord," said James, "I have many questions to ask you concerning
my poor Vipont, the trial of the Lady Seton, and her mad brother's invasion
of Inchkeith single-handed. Faith! he is quite a devil of a fellow! But first
tell me what rumour is this, of cannonading in the river Forth, which
reached me this morning."

"Oh, it was merely Monseigneur Claude d'Annebault, admiral of France,


who has brought the new ambassador, escorted by eight frigates, which
have anchored off the Beacon rock at Leith, where they saluted the Scottish
flag, and the ships of Sir Robert Barton replied by their culverins."

"France," said James, sadly; "and this ambassador?"

"Will pay his respects to your majesty to-morrow."

"By my soul, I thought it was the Lord Howard with the fleet of my
uncle Henry; and that he had come to blows with stout Sir Robert."

"A new ambassador from England is also coming hither."

"Ah!—and concerning what?"

"A league with Henry. Need I implore your majesty," said the cardinal,
in the most impressive tones of his persuasive voice, "need I implore you to
beware! He comes to crave an interview, that Henry may instil into your
heart his own hatred of France and heresy to God."

"Hatred to the France of my Magdalene—the France of Scotland's old


alliance! Nay, my Lord Cardinal, I need no warnings. There is a grasping
and aggressive spirit in England, of which Scotland should beware; but can
my heretic uncle imagine that he will induce me to bring about here the
same change of religion that he, by a single word, has wrought in
England?"

"He cannot; but he thinks that England will never be thoroughly


Protestant, or at least opposed to Rome, while Scotland remains Catholic
and true; thus his whole soul is bent on breaking that continental alliance
which aggravates, as he thinks, our old and just hostility to his people."

"Is not the alliance broken? My poor little Magdalene!"

"Thou hast most unwisely and unjustly permitted Sir David Lindesay of
the Mount, George Buchanan, and others, to satirize the bishops and orders
of clergy: yet, in the name of the latter, I have this day approached your
majesty, to offer an annual subsidy of fifty thousand crowns from the rents
of the kirk, to enable you to defend yourself more ably against England and
her allies the Portuguese."

"This is well! the crowns are right welcome."

"An ambassador——"

"What—another?"

"Is coming from Rome, with a consecrated sword, which with his own
sacred hands his Holiness has whetted on the altar-stone of St. Peter—yea,
whetted against the English people and their king, whose fleet is now out on
the high seas to intercept the envoy and his gift."

"Indeed!"

"Thou seest how far these English will dare."

"If the ambassador is taken before Barton can reach the Downs, then, d
—n England—we'll go to war with her! and here into your hands I commit
the books written by Henry, and brought hither by the Welsh bishop of St.
David's, wherein he defends so boldly the principles of Luther."
"Good; I shall burn them on the first occasion, before my gate at St.
Andrew's," replied the cardinal, as he threw them outside the chamber door
to his page who waited in the gallery.

"With thy advice I broke off the meeting which Henry proposed at York;
so we may now prepare for war in earnest—a war that will pour forth our
Scottish blood like water; but on the plains of our hereditary foe. The
Scottish people should be ever like a drawn sword—the king being the hilt,
his subjects the blade."

"Gladly will I head the army," said the cardinal, whose eyes sparkled.

"Nay," replied James, dryly, and with a smile; "should war be resolved
on, I shall lead the army in person, as my predecessors have always done.
What say the laws of the church on prelates leading armies?"

"It is forbidden by the canons of John VIII."

"Sir Oliver Sinclair of Ravensheugh is a brave serviteur of the crown,


and he may be my lieutenant-general."

"Sire, Sir Oliver of Ravensheugh is a mere laird, and no lord will follow
him to the field. But we are well prepared for any emergency. The Earl of
Buchan commands on the eastern marches, the Lord Sanquhar on the west;
and the Lord Tester commands the middle. Their paid bands of horse and
foot are ever on the alert. Our ships of war are not so numerous as they soon
shall be; but they fully equal those of England in every respect, for the
Unicorn, the Salamander,* the Morischer, and the Great Lion, are each as
large, if not larger, than the boasted Harry. Then we have the little frigate
taken by Sir Robert Barton from the Admiral Howard, in Yarmouth Roads."

* These two were burnt by the English, in 1544.

"The Mary Willoughbie?"


"Mounting twenty culverins, besides arquebuses and crossbows; and we
have six others on the stocks at the New Haven. Including those which
came from France," continued the cardinal, consulting his note-book, "we
have one hundred and fifty pieces of cannon in our arsenal; and Scotland
was never better prepared for war than at the present hour—nay, not even in
the days of James IV."

"For which I thank the ability of your eminence," replied James, who
cordially disliked his uncle Henry. "My father, James IV., entered England,
whenever he chose, at the head of an army; but I, unfortunate! have a stiff-
necked people, who, much as they love me, will not fight unless their
parliament tells them to do so; and, worse than all, cardinal, the people—
hate thee!"

"Faith, sire, they are ready to hate any one—the rabble."

"Impatient of thy power and princely offices, they think the royal
authority will soon sink to nothing beneath the shadow of so great a
minister. But what matters it? I long for war, because I am weary of life;
while thou longest for it, simply because thou hatest the English. Lord
cardinal, I am come of a doomed race," said James, with a shudder, as the
vague terror that his house was fated to fall with himself came upon him,
and a gloom spread over his manly brow. "I remember me of a prophecy
that was made by a weird woman of Strathgryffe to Allan the great steward,
'that never one of his race should comb a grey head;' and fearfully hath that
prophecy been verified!"

The eyes of the good king filled.

"Come my time when it may," he continued, "I know that my dear


Scottish subjects will remember me long. Cardinal, my people call me king
of the puir, and I am prouder of that title than the thorny crown the
Alexanders, the Constantines, and the Braces have left me. The blessings of
the poor and the lowly attend me when I walk abroad, without guards,
without retinue, without arms. I hate the nobles, for they are ever ready to
barter their country and their God for foreign gold: and Scotland's nobles
will one day be Scotland's destruction. Pardon this honest vanity; but I feel
that to reign in the hearts of my people is a great and glorious thing. There
are many kings in Europe, but not one is called the father of his poor but
James Stuart of Scotland. I am ever among them. I visit the highways and
the byways, the gloomy streets, the miserable garrets, and the famished
cottages where pestilence, or poverty, or tyranny have been. I know where
misery is, or wrongs are endured. Disguised as a beggar, I discover them; as
a king and a gentleman I alleviate or avenge them. The hard hands I have
shaken, and the humble hearts I have gladdened, will serve me to the last
gasp; and the ingleside where a king has sat and supped his kail with the
gudeman, or toyed with his bairns, will long be remembered in tradition
when the king and the clown are blended in one common dust. Thus I feel
with joy that I shall go down to my grave at Holyrood with the blessings of
my people, and shall be remembered long in the land, which my father
bequeathed me from the Field of Flodden."

The king paused; and the cardinal, remembering his pledge to Father St.
Bernard, deemed this the best opportunity for opening the trenches.

"Sire, this is a good and holy frame of mind," said he, "and I sometimes
see the truth of what Buchanan teaches (heretic and republican though he
is) that impulses to good or evil are common to all ranks of men, and in
these respects all men are equal."

"Cardinal, all men are equal, too, in the grave. Were a beggar laid beside
me at Holyrood, he would be as great as me, and I no greater than he."

The cardinal could scarcely repress a gesture of impatience.

"I fear me," said he, "that the solitude of Falkland oppresses your
majesty's mind?"

"It is in solitude that God speaks most to man; and I, oh cardinal, have
been in solitude since my poor Magdalene was lost," replied James, kindly
caressing the little dog.

"She is not lost, but gone before."

"Cardinal," said James, looking up with his hazel eyes full of tears, "I
pray for her daily."
"One act of mercy performed in her name and memory, will do more for
the soul of Magdalene than a thousand prayers."

The king looked earnestly, perhaps suspiciously, in the dark and majestic
face of Beaton, and said,—

"Your eminence actually means this?"

"Most solemnly!"

"Then what is this act of mercy?"

"A pardon for the Lady Jane Seton."

James's bright eyes flashed with fire, and he twisted his brown
moustache with anger.

"Now, by the Holy Communion, this is too much; a pardon for the
destroyer of Magdalene of France—for this daughter of a Douglas, and
sought in this tower of Falkland, the very chamber where her sire the Lord
John of Ashkirk, and her grandsire Sir Archibald of Kilspindie, detained me
once a prisoner, with a guard of some five hundred Douglases, from whose
surveillance I had to fly like a thief in the night! Lord cardinal, it is
impossible."

It was seldom that James refused him a favour, and his eminence was
piqued.

"There is but one day now, and I beseech your majesty to consider well."

"I have considered well. The Countess of Arran and I talked over the
matter for three hours yesterday."

"The Countess of Arran!" muttered the cardinal; "women—women!


there is ever mischief where they are concerned. It would have been well
had they been altogether omitted in the great plan of human society."

"And to lessen this evil to the public thou keepest a dozen of them shut
up in the tower at Creich, all fair and jolly damosels," said the king, with
something of his old raillery; "truly, lord cardinal, my subjects of Fife are
much indebted to thee."

"I assure your majesty," said the cardinal, with increasing pique, "that to
the best of my knowledge the whole trial and accusation hath been the
prompting of revenge in Sir Adam Otterburn of Redhall."

"Of my lord advocate? Impossible! why, the man is virtuous as Scipio,


and upright as Brutus."

"But in their excessive zeal, the judges have wrongly construed the
depositions. I implore you to reflect; her death will make an irreparable
breach between the races of Stuart and Douglas. War alone will not make a
monarch illustrious. The splendour of valour and chivalry dazzles for a
time; but a noble action lives in the memory of the people for ever."

"True; but beware, lest I deem thee a follower of Angus."

"I follow a Master who is greater than all the princes of the earth,"
replied the stately prelate, warming; "and the opinions of the poor worms
that crawl on its surface are nothing to me."

"Is this the fag-end of some old sermon?"

"Sire, thou mockest me, and I have not deserved it of thee," said the
cardinal, rising with dignity; "but let not the ambassadors of foreign princes
see thy weakness, and how thou carriest thy vengeance even against a
helpless woman. Was it for such an act as this, that Francis the
Magnanimous sent thee the collar of St. Michael; that the great Emperor
Charles, the victor of sixty battles, sent thee the Golden Fleece; and English
Henry, his noble Order of the Garter? I trow not. Glory and virtue cannot
exist without mercy—the first is but the shadow of the other two. In this
case, close thy heart against hatred, and thou wilt soon become merciful,
even to these hated Setons and Douglases. Sire, sire, to thy many good
actions add but this one more."
"Cardinal, thou pleadest well; but sayest nothing of my gallant Vipont,
my comrade in many a hairbrained French adventure. I would have given
my best horse and hound—even Bawtie, to have seen him confronting
Abbot Mylne and his fourteen black caps! But the sorceries, the vile
sorceries of his lady——"

"Are about as true as the miracles of Mahomet."

"How! Did she not confess them to the whole bench?"

"True," replied the cardinal, with a smile; "when her tender limbs were
being rent asunder by the rack."

"The rack! the rack! Oh, was it only on the rack she confessed these
things?"

"As thou, sire, or I would have done, under similar circumstances."

The king seemed thunderstruck.

"A pen! a pen! though a Seton, and a Douglas's daughter, too, I forgive
her—she is saved."

A few hours after this, when the sun was setting on the East Lomond,
Lewis Leslie of Balquhan, mounted on a fleet horse, with the pardon,
signed, sealed, and secured in a pouch that hung at his waist-belt, was
galloping through the parks of Falkland, on his way to the capital.

CHAPTER LII.

THE LAIRD OF CLATTO.


"Farewell Falkland, the fortress of Fyfe,
Thy polite park, under the Lawmound law;
Sumtyme in thee I led a lusty lyfe,
The fallow deer to see thaim raik on raw,
Court men to cum to thee, they stand grait aw,
Sayand thy burgh bene of all burrowis baill,
Because in thee, they never gat gude aill."
Complaynt of the Papingo.

By the machinations of Redhall, and the subtle ability of Birrel, his


messenger, there lay many a deadly barrier, and many a sharp sword,
between the gallant Leslie and the city of Edinburgh.

The last rays of the sun had vanished from the furzy sides and green
summit of the East Lomond, once called the Hill of the Goats, in the
language of the Celtic Scots, when he quitted the park of Falkland, and
struck into an ancient horseway, which, under the shadow of many a
venerable oak-tree, led him towards Kirkforthar; and soon the hill of Clatto
became visible as it rose about five miles distant on his left.

At that very time a party of horsemen, well armed with lances, two-
handed swords, and daggers, and wearing steel caps, with jacks of mail,
rode round by the edge of a great and dreary peat-moss, which then lay at
the base of Clatto Hill; and passing the old chapel of Kirkforthar, concealed
themselves in a thicket of beech-trees, near an ancient mill, some moss-
grown fragments of which are still remaining in the highway. There two of
their number dismounted, and borrowing a couple of shovels from a
neighbouring cottage, with the utmost deliberation, after carefully removing
the green turf, proceeded to dig a grave.

Of these horsemen, fifteen were Redhall's own vassals, led, not by


Birrel, for that arch-conspirator had reserved unto himself another part in
this cruel and cowardly drama, but by Tam Trotter and Dobbie, both of
whom felt their personal importance and dignity increased to an unlimited
extent by this command; and Dobbie's cat-like visage wore a comical
expression of martial ferocity, as it peeped out of the depths of a vast helmet
of the sixteenth century.
The other horsemen were led by John Seaton of Clatto, the
representative of a family which had long been infamous for its lawless acts
and readiness to perform any outrage. The ruins of their tower are still to be
seen at the south-east end of Lathrisk, as the parish was then named.

The old road from Cupar to Kinghorn passed through a gorge, called
Clatto Den, and in the face of the mountain which overhung that narrow
bridlepath there lay a cavern, the mouth of which was concealed, but whose
recesses afforded a subterranean communication with the vaults of the
strong tower above; and there the bandit family of Clatto were wont to rush
out and butcher those unsuspecting persons who rashly passed through the
den alone, either by night or by day. James IV., when travelling with two
esquires, had narrowly escaped assassination there; but cutting a passage
through, escaped, leaving one of his assailants minus a hand. In his
ignorance of the owner's free propensities, the king took shelter in the
tower, when finding that Seaton's sixth son was maimed, the guilt of the
family came to light; the secret passage to the tower was discovered; the old
ruffian laird and all his sons were hanged, save John the youngest, who,
being then a child, escaped to figure on the present occasion.

Justice was more severely administered under James V.; thus, the
exchequer of the Laird of Clatto being somewhat low, the accoutrements of
his fourteen horsemen were rather dilapidated and rusty; but, like their
riders, the horses of his troop were fresh, strong, sinewy, and active. Having
a plea anent meithes and marches with the Boswells of Dovan, the promise
of a decision in his favour had drawn him from his lair on the dark errand of
Redhall.

The cavern that lay below his tower is now concealed, by the impending
side of the den having fallen down a few years ago, and choked up the
entrance; but the peasantry still point to the place with fear and abhorrence.

Rendered thirsty by a six miles' trot from the tower of Clatto, John
Seaton, while his men were coolly digging a grave, went boldly to the mill
of Kirkforthar and demanded a cup of ale, upon which the miller gave it
submissively, and without asking a question, for he knew that it was as
much as the lives of his whole family were worth, to ask on what errand the
Laird of Clatto was abroad in the gloaming.
"Harkee, miller," said he, with a grin, exhibiting (between his bushy
moustaches and beard, which almost concealed the cheek-plates of his open
helmet) a set of those sharp white teeth, which bespeak a strong healthy
fellow, who is often hungry but always happy: "Harkee, carle miller; haud
fast your yett, steek close your een and lugs, and steek them ticht, for the
next twa hoors; and tak' ye tent to hear nocht else, but ablins the splash o'
your milnwheel, till the mune glints abune the moss."

"Langer, gif it please ye, laird," replied the poor miller, trembling.

"Ou, that will be lang enow; but tak' tent o' my words; hear ye nocht, and
see ye nocht; or I may come doon by the Mossend some braw nicht, and the
mill o' Kirkforthar will be toom o' a tenant in the morning; keep close by
your ingle cheek, carle, for the chields o' Clatto winna thole steering."

And carefully wiping a few drops of ale from his cuirass, which was
magnificently cut, worked, and inlaid with the most rare damascene work,
he left the low thatched mill, and sprang on horseback.

Meanwhile Leslie was galloping by the northern base of the East


Lomond. His horse was a strong and active roadster, which he had received
from the king's master-stabler. Fortunately he had taken the precaution to
retain his armour, which was a ribbed Italian suit, studded with gilded nails,
and on the globose cuirass of which his coat of arms were engraved. His
gauntlets were overlapping plates, without finger-scales, thus, with the
ample steel hilt of the sword, forming a double protection for the right hand.
His arms were a long straight rapier and dagger, and at the bow of his
demipique saddle he had a pair of firelock dagues, or pistols. The latter
every gentleman carried when travelling; and the former were as necessary
to a cavalier of the time as his feather or spurs.

His horse having lost a shoe, the delay caused by the necessity of having
this loss repaired by a roadside Vulcan made the evening dusk before he
approached the mill of Kirkforthar. The summer moon shone brightly in the
blue sky, and clearly and strongly the outlines of wood and mountain rose
against it.
On Leslie's right rose the steep Lomond; and on his left extended the
vast moss, amid the wilderness of which many a deep pool of water lay
gleaming in the moonlight. The district was desolate and wild; but no idea
of danger or of molestation occurred to the mind of the solitary horseman,
who rapidly approached the mill of Kirkforthar, where the dark foliage of
some old beech-trees overshadowed both sides of the way; and where, save
the cry of the cushat-dove, all was still as death. A red spark that glimmered
among the trees, alone indicated where the mill lay.

Leslie checked the speed of his horse, as the road plunged down into this
obscurity, which he had no sooner penetrated, than he found his course
arrested by two bands of horsemen, who wheeled round their ranks from
each side of the road, barring their passage by their levelled lances and
uplifted swords. Well was it for Leslie that his fiery horse made a demi-
volte, giving him time both to escape their weapons and unsheath his own.

"Make ye way, sirs! I am on the king's service!" he exclaimed, still


backing his horse, but disdaining to fly. "Plague! the sheriff of Fife has
surely bad deputies! But, whoever you are, rascals, the life of Balquhan for
the best life among ye!"

And dashing spurs into his horse, he broke through the whole band like a
whirlwind, thrusting one through the body, bearing down another,
unhorsing a third with his foot; and passing unhurt through the hedge of
steel around him, left John of Clatto and his ruffians to deposit one of their
own number in the grave they had dug so carefully in the thicket near the
mill.

He heard behind a storm of oaths and outcries, mingled with the clash of
arms, and the rush of galloping hoofs, as the horsemen broke tumultuously
out of the wooded hollow, and poured along the highway, in fierce pursuit
of him. Heedless of their taunts and shouts, Leslie spurred on: he had now
been made aware that there were those upon the road whose interest it was
to intercept him. On, on he went by the skirts of the desolate and
moonlighted moss, and his anxiety was not lessened by the reflection that
he had to pass by the Tower of Bandon, whose proprietor was his enemy;
and in a few minutes he saw the square outline of this fortalice, with its
angular turrets and grated windows, rising above the roadway, among a
group of old ash-trees.

The pursuers were close behind.

Leslie was almost tempted to turn towards the moss; but to one so
ignorant of its paths, such a measure might prove a certain death, while the
risk was scarcely less in keeping near the barony of Bandon. Half-a-mile
before him, on the open muirland, he saw several men on horseback, and
his practised eye soon discovered that they were twelve in number, and
armed, for the moonbeams were reflected from twelve helmets. Then his
heart became filled with rage; for though he knew not why his path was
thus beset, he knew that if he were slain, and the pardon was not delivered
by a certain hour in Edinburgh, the unhappy Jane Seton, the promised bride
of his friend, would assuredly be led forth to perish by a shameful and
frightful death.

Many of the troop from which he had escaped, not less than twelve,
perhaps, were scarcely a hundred yards behind him; now he saw as many
more in front, and his forebodings told him they were the Lindesays of
Bandon. At Balbirnie there stood an ancient cross, erected by a gentleman
of the neighbourhood who had slain another at that place; and this cross
(which is still standing) Leslie knew would afford him a sanctuary, if his
pursuers were old Catholics; but he remembered that the Reformation had
made vast progress in Fife, and that its proselytes would not hesitate to
violate any sanctuary; so, instead of pressing onward to gain this bourne,
supposing that the direct road might be beset still further on, he turned
abruptly to the left, and plunged down a narrow strath, which led, as he was
aware, towards the village of Markinch and the strong castle of the Lundies
of Balgonie.

A shout burst from the horsemen on the muir, on finding that he thus
avoided them; and, joining with those who came from Kirkforthar, they all
urged their horses to the utmost speed to intercept the gallant messenger.
Many a dague and petronel were fired after him, and he heard the balls, as
they whistled sharply past his ear, crash among the branches of the wayside
trees, or sink into the flinty road; but after some twenty or thirty shots, the
firing ceased, as the troopers rode in such haste that they had not time to
reload their firearms. On, on came horses and men at headlong speed,
rushing, a troop of evil spirits, along the moon-lighted strath; now dashing
through coppice and underwood, then splashing through a brawling
mountain burn; now sweeping noiselessly over the yielding moss and
heather muirland, and anon breasting gallantly up the pasture braes: but
Leslie, being mounted on one of King James's best horses, fresh from its
stall at Falkland, though he did not leave his pursuers altogether behind,
was yet enabled to keep a considerable distance between them and himself.

And now, upon a little eminence, the village of Markinch, with its
venerable square steeple of the eleventh century, arose before him, and near
it he fortunately left almost the half of his pursuers, floundering up to their
girths in the deep and dangerous marsh which encircled the village on every
side save one. Here to halt was vain; for the unscrupulous Lairds of Clatto
and Bandon had men enough to sack and destroy the whole kirk-hamlet; so
forward pressed the fugitive, intent on reaching the castle of Balgonie, or
the ancient mansion of the Beatons of Balfour, where the archbishop of St.
Andrew's and his nephew, the great cardinal, were born. On, on yet! and he
soon found himself among the woods of the Leven; dark and thick, old and
stately, the beeches were in the full foliage of July, and the dense old
Scottish firs intertwined their wiry branches with them: and now the river,
broad, deep, and hoarse, in the full fury of its summer flood, swollen by a
night of rain, lay rolling in foam before him; and upon its opposite bank
rose, from a wooded eminence, the strong and lofty donjon tower of that
time-honoured, but now extinct race, the brave old Lundies of Balgonie.

Glittering in the moonlight, like a silver torrent, the beautiful Leven


swept out of the far and dark obscurity of its foliaged dell, and in its crystal
depths (save where the foam-bells floated) the sombre outline of the castle,
with its turrets, and the steep knowe on which it stood, with all its waving
trees, were reflected in the deep and downward shadows.

There were not less than twenty mounted spearmen still upon his track,
and, lo! a deep, fierce current lay foaming in his front. On a level sward,
Leslie paused with irresolution, and before plunging into the stream,
surveyed it, but surveyed in vain to find a ford.
He looked back. The hill he had descended was covered with whins and
scattered trees; and there, far in advance of their comrades, came four
horsemen, who were now close upon him. With a fervent, almost a
ferocious prayer to Heaven, he drew his sword and awaited them, for at the
first glance he discerned that one of the four was his enemy Bandon, who,
to breathe his panting horse, advanced leisurely at a trot before his three
immediate followers.

"Guid e'en to thee, my light-heeled Leslie," said he, with a sardonic grin;
"thou hast gien us a fast ride and a far one!"

"Beware, Bandon; I ride this night on the king's service."

"I ken that well."

"And still thou darest to molest me?"

"Yea, would I, though ye rode on the errand of the king of hell instead of
that of the King of Scotland. Have at thee—for thou art a Leslie of
Balquhan!"

"Beware, I tell thee, beware! My life is not my own to-night," cried


Leslie, guarding the impending stroke of Lindesay's uplifted sword;
"beware thee, till to-morrow only. I am the bearer of a royal pardon to
Edinburgh."

"To thy grave alone thou bearest it!" cried the other, furiously.

Leslie parried the blow, and then replying by a thrust at the throat of his
antagonist, before withdrawing his sword, bestowed a backhanded stroke at
another horseman, who had covered him with his brass petronel, a stroke
which rendered his better arm useless. Another deadly thrust relieved him
of a second enemy, and then he had but two to deal with.

Round and round him they both rode in circles, but by point and edge he
met their cuts and thrusts; till observing that Bandon was close to the edge
of the stream, he suddenly put spurs to his horse, and charging him with the
utmost fury, by a blow of his foot forced him right over the bank, where his
horse fell upon him, and with its rider sank into the river. There Lindesay
became entangled beneath the animal, which snorted, kicked, and plunged
so violently, that he was swept unresistingly away with the current and
drowned. Next morning the miller of Balgonie, on finding his machinery
stopped and the dam running over, was horrified to see a horse and its rider,
in armour, lying drowned and jammed under the great wooden wheel of his
mill.

A volley of petronels from the bank above Leslie left him no time for
further defence or reflection; and with a shout of defiance he leaped his
horse boldly into the stream, and, regardless of the bullets which plunged
into the water incessantly, exerted every energy to gain the opposite bank,
using his hands and knees, half swimming, to relieve the animal of his
burden (which was not a light one, the rider being in armour): keeping its
dilated nostrils above water, and yielding a little to the current, he
ultimately crossed, successfully and securely.

With flattened ears and upraised head, the broad-chested steed breasted
gallantly the foaming water, and snorted with satisfaction on feeling the
firm ground at the opposite side, where Leslie uttered a shout of triumph as
he scrambled up the bank, and thus by one bold effort found himself free.

Oaths and cries of rage resounded among the woods behind, and many a
trooper urged his horse towards the brink, but their hearts failed them, and
not one dared to cross the deep and rapid Leven, by which their intended
victim had been saved and their leader swept away before their eyes. The
lieutenant of the king's guard now leisurely examined the knees of his horse
and the girths of his saddle; looked to his sword-belt and spur-leathers;
recharged his petronels, and glanced at the pouch which contained the
pardon of Jane Seton. He then wiped his sword and remounted.

Reflecting that the river was now between him and his enemies, that he
was several miles out of the direct road, and that (except the ducking) he
was not in the least the worse either of the ride or the combat, he resolved,
instead of seeking shelter either at the place of Balfour or the castle of
Balgonie, to push onwards to Kinghorn.
The ramparts of this stronghold, which are eighty feet in height, were
glimmering in the moonbeams, above the tossing foliage, as he descended
into the hollow which lies to the south of it, and then turned westward, little
thinking that the ferocious Laird of Clatto, with Dobbie, Tam Trotter, and
some fifteen horsemen, in anticipation of such a measure, had long before
wheeled off to the right, and were pushing on the spur towards the
Kinghorn road to intercept him.

CHAPTER LIII.

THE FIGHT AT INVERTEIL.


"Let us hasten to receive them,
Placing in the foremost ranks,
Those who bear the arquebuses;
Let the horsemen next advance,
With the customary splendour
Of the harness and the lance."—CALDERON.

With a heart divided between emotions of rage and exultation, the


fugitive messenger rode towards Kinghorn.

The aspect of the tract of country he crossed is very different now from
what it was in those days. Many places that are bare pasture lands were then
covered by dense thickets of natural wood; other places, that are now fertile
and arable, were covered with broom and whins of such gigantic size that
horsemen might have been concealed among them; while all the straths and
glens were filled with the water which then flowed through innumerable
mosses and marshes. Streams, which were then impassable rivers, have
now, by the drainage of the land and other agricultural improvements,
shrunk to mere burns or mountain runnels; while those which were then
burns and trouting streams, have in many instances totally disappeared; and
waters, such as those of the Boathouse bridge in Linlithgowshire and the
Eden in Fifeshire, which had ferry-boats plying upon them, are now
scarcely deeper or broader than a wayside drain. Thus, when, to save time
and the trouble of riding round in search of fords or bridges, the brave
Leslie, all heavily armed as he was in Italian plate, boldly swam the
winding Loctie and the Ore, near the Spittalcots, he performed two gallant
feats, for then those waters foamed in deep, broad currents between torn
and rugged banks, with a breadth and force very different from what they
exhibit in the present day, even during the fury of a winter speat.

But before he had entered on the moss and moor that lay between the
Ore and an old mansion named the Temple Hall, which then belonged to the
knights of Torphichen, the waning moon was disappearing behind the hills,
and shed a cold, pale light on the dreary waste that spread before the
solitary rider.

Having lost all traces of the ancient drove-road, which had guided him
thus far, Leslie walked his horse forward with caution, to avoid the peat-
bogs and pitfalls that now surrounded him; while, impelled either by the
dreariness of the solitude on which he was entering, or by some vague
presentiment of danger, he narrowly observed every bush and hillock as he
approached, and listened for any passing sound.

The moon seemed to rest on the summit of the distant hills, the solid
outline of which rose blackly against the blue sky. Light clouds were
floating across her surface; but a clear white light was shed along the
countless ridges of the muir—the moss-covered roots of an old primeval
forest—which resembled the waves of a motionless sea.

A sharp, low whistle on his left, and somewhat in advance of him, made
Leslie look in that direction; and he saw the moonbeams reflected back
from something bright, that too evidently was not moss-water, but polished
steel; while two or three light puffs of smoke curled upward, showing
where the matches of petronels were being blown for active service.

The moss was full of armed men!


"Fool that I was not to byde me at Balgonie!" thought Leslie, as he put
spurs to his jaded horse, and quickened its speed to a hand-gallop. By his
devious route he had now ridden fully twenty miles, over a frightful tract of
country, full of steep hills and rocky glens, deep morasses, brawling
torrents, and hills covered with forest and brushwood; he had forded three
swollen rivers, and thus, like himself, his horse was already becoming
exhausted.

"Hollo, Balquhan!" cried a mocking voice; "whither so fast? Is your


lady-love sick, or is your house on fire?"

A shout of derisive laughter, together with the explosion of four long


petronels, followed this remark; and Leslie became aware, from the sudden
bound and snort of pain given by his horse, as it shot away like the wind,
that the poor animal was wounded; one bullet had penetrated its near flank,
and another had grazed its ears.

"The devil! 'tis quite an arquebusade! But I am getting used to such


music to-night," thought Leslie, as he gave a wistful glance at the Temple
Hall, which was not far off. All property which belonged to the Knights of
St. John in Scotland afforded a safe sanctuary from debt and danger, and did
so until a recent period; but Leslie knew too well that his present pursuers
would violate the holiest shrine between Cape Wrath and the English
frontier to reach him; and that he had nothing to trust to but the blade of his
sword and the heels of his horse; for by the number of ambuscades,
prepared in every direction, it became evident that his enemies, whoever
they might be, were bent on his destruction.

Tall lances and bright helmets flashed in the moonlight, as the dark
forms of many a horse and man arose from behind the heather knowes and
clumps of moss and whin to join the chace; and Leslie found that again the
ferocious John of Clatto, with all his band, was riding on his trail.

Though the balls which had wounded his horse caused a great effusion
of blood, they acted as spurs of fear and pain to accelerate its speed; and
Leslie soon heard the shouts, the clank of arms, and the rush of galloping
hoofs growing fainter and fainter with every bound that his fierce strong
charger made. The banks of the Ore, the desolate muir, and the grey Temple
Hall soon vanished in the distance; and he saw the spire of Kirkaldy, and its
long and straggling town, rising on the left, from the low flat shore of the
Firth, which lay beyond it, glimmering in the last light of the moon, and
bringing forward, as from a brilliant background, the innumerable roofs and
gables, clustered chimneys, and turretted edifices of the venerable burgh.
Near him rose the hill and castle of Raith, where Sir John Melville, the
great Reformer, dwelt; and nearer still, embosomed among summer woods,
lay the Abbotshall, a seat of the abbot of Dunfermline, the site of which is
still indicated by an old stupendous yew that grew before its gate. Right in
the fugitive's front lay the broad green links of Kirkaldy, and the glittering
estuary, with the black rocky promontory of Kinghorn jutting boldly into its
waters.

The strength of his horse was failing fast; its eyes were blinded, and its
head was drenched in the blood flowing from its wounded ears; and he felt
certain that, to turn from his straightforward course, to seek shelter in the
neighbouring town, would only serve to exhaust it more. He knew well that
the brave animal was dying beneath him, for with every convulsive bound
of its foam-covered haunches, the blood-gouts gushed forth upon the sandy
turf.

Balwearie, in older times the birthplace of the wizard, Michael Scott,


was left behind; and now the hoarse brawl of the Teil—a flooded torrent—
rang before him. He gave his horse the reins, and furiously applying the
spurs, keeping his head back and his bridle-hand low, as he urged it to the
flying leap. Lightly it rose into the air, cleared the stream, with all its banks
of rock and bed of stones, but reached the opposite side only to die; for the
noble horse sank down with its forehead on the turf, and after making more
than one fruitless effort to rise, rolled heavily over, stretched out its legs
convulsively, and with that mournful cry which few hear, but a horse alone
can give, expired.

At that moment, with brandished swords and panting steeds, six


horsemen appeared on the opposite bank; and the exhausted Leslie knew
that nothing now remained for him but to sell his life as dearly as possible.

He was now but two miles from Kinghorn, and after all his exertions, he
felt how hard it was to die; and reflected that, with his life, the pardon of
poor Jane Seton would be futile, or forfeited, as she would inevitably be put
to death before additional tidings of the king's favour came from Falkland.
The very excess of his bitterness gave him a superhuman courage, and
alone, on foot, he resolved to confront them all; but in doing so, to use
every stratagem.

With the rapidity of thought, and unseen by them, he threw himself close
beside his dead horse, the body of which was greeted by a shout of fierce
exultation.

"Awa and on!" cried John of Clatto; "for gif ance he wins the burgh o'
Kinghorn, the tulzie will be owre, and I sall tyne my plea anent the meithes
and marches. On, on, ye fashious fules; hae your naigs nae mair mettle than
the mules o' monks?"

Leslie grasped his drawn sword with both hands, and as the Laird of
Clatto leaped the Teil, with one fierce backhanded stroke hamstrung his
horse the moment its hind heels alighted near him.

With a tremendous curse, this ferocious rider with his steed tumbled
prone to the earth; and as they fell, Leslie sprang up, and by the same daring
manoeuvre, unhorsed another, and slew him as he fell. Then rushing to the
summit of the bank, that he might have all the advantage the acclivity could
afford him, he stood resolutely on his guard. The rest of the band were yet
far off, and by their leisurely trot it was evident that their horses were
breathless and blown. "John of Clatto!" exclaimed Leslie, as he engaged
that person furiously, each swaying his sword with both hands on the hilt;
"thou unhanged thief and son of a thief! now—now shalt thou receive the
coward's reward."

"Fause coof!" retorted the other, with one of his ferocious laughs, as with
a deadly coolness and activity he dealt his thrusts, while the force of his
parries announced that his eye was sure, and his wrist was of iron, as he
hewed away with his long and trenchant sword; "Coward? ha! ha! 'tis a
name never kent by a son o' auld Symon o' Clatto. Strike weel and surely,
my bauld Balquhan, for by God and Macgriddel, I sall handsell thy braw
harness in thy hettest bluid."
"Dog! it hath been handselled by the swords of better men!" exclaimed
the furious Leslie, as by a single sweeping stroke his heavy sword beat
down the guard of his adversary, breaking his blade like a withered reed,
and, cleaving his helmet through the very cone, killed him on the spot. A
curse was half uttered by its quivering lips, as the body fell backwards over
the bank, and lay half merged in the water of the Teil. With his great natural
courage exasperated to a terrible pitch by the knowledge that he must
inevitably perish at the hands of these cowards, Leslie fiercely met the
horsemen as they leaped the stream, and in succession fell sword in hand
upon him. A shower of blows rang upon his tempered helmet, his eyes
swam, and, amid a cloud of fire, it seemed as if a myriad of men and horses
had assailed him, and as if as many swords were ringing in his ears, and
flashing before his eyes.

He was soon beaten to the earth, and several men sprang from their
horses to despatch him, when the shots of two petronels were heard, and
two assailants sank heavily, dagger in hand, beside him, tearing up the grass
with their hands and teeth in the agonies of death. A rush of horses
followed, and Leslie found himself free!

Clatto's men had fled; and a young cavalier stood before him richly clad,
with three tall feathers in his bonnet; he was mounted on a superb black
horse, and in each hand had a petronel, from the barrels of which the smoke
was curling. The drawn swords of his six mounted attendants were
gleaming in the bright twilight of the July morning, for day was already
glimmering over the far horizon of the German Sea. The features of this
deliverer were noble, but delicate; his eyebrows and closely-clipped
moustaches were coal-black, his lips were red, and cut like those of a
woman, but his large dark eyes sparkled with courage and animation.

"Now, by Heaven, 'tis our loving cousin and clansman, Balquhan!" he


exclaimed; for in those days, "when old simplicity was in its prime," every
man of the same name in Scotland was designated loving cousin.

"Sir Norman Leslie," said the lieutenant of the guard, as with


thankfulness and respect he greeted the gallant Master of Rothes, the son
and heir of the earl, his chief, "thou hast saved me from a cruel and bitter
death! what do I owe thee?"
"Two brass bullets at a similar juncture."

"May it never happen!" said the young baron, to which the master
replied with a reckless laugh, in which his followers joined.

"Balquhan," said he, "this gentleman is your cousin—my uncle, John of


Parkhill. Here are three men and two hamstrung horses lying on the grass!
By St. Mary! my true Leslie, thou hast this night handled the sword as if it
had been thine own invention."

"Anent what hath all this been?" asked John Leslie of Parkhill, an elderly
gentleman, sheathing his sword.

"Heaven only knows, sir," replied Leslie, as he caught the bridle of a


riderless horse, and leaping into the saddle began to examine the petronels
that were attached to it.

"They seem to have found you a rough jouster!"

"I am riding on the king's service, with a pardon for the Lady Seton."

"The Lady Seton!" they all repeated, in varying tones of astonishment


and satisfaction.

"Yes, sirs, I am bound for Edinburgh, and have been thrice beset by
horsemen, and thrice have swum a river, the Leven, the Ore, and the
Lochtie!"

"Sheriff of Fife, what say you to this?" said Parkhill to Norman Leslie.

"That it shall be looked to, and that sharply," replied the young Master of
Rothes, as he replaced his pistols in the holsters; "a harmless rider, a
messenger of mercy on God's own service, to be molested thus!"

"Besetting the highway—'tis a capital crime."

"Perhaps John of Clatto (for it was he) thought that messengers of mercy,
or of Heaven, seldom ride in coats of mail."
"To thy spurs, Balquhan, and on!" said the master; "the poor dame Seton
will assuredly fall a victim to the malice of the Hamiltons at midnight—this
midnight, for see, the day is dawning. They were setting the stake, and
tearing the faggots, on the castle bank, as we left Edinburgh by the West
Port last night."

"I go to the King's Horn hostel," said Balquhan; "would I were there, for
I am drenched like a water-dog, and well nigh wearied to death. Farewell."

"Take ye care, sir!" cried John of Parkhill.

"Come now, you jest, my cousin," said the lieutenant, jocularly; "does a
Leslie ever fall from his horse?"

"I only mean, beware thee while at Kinghorn, and keep thine errand
secret; for there are several men of the house of Arran in the burgh, and
their nags are stabled at the very hostel thou hast named."

"Nay, nay, uncle of mine," said the fiery Norman, "no Hamilton would
arrest the pardon of any woman; then how much less that of a lady of high
name and gentle blood!"

"Nephew Norman, we know not the tricks of which the Lord Arran and
his faction are capable; and to whom shall we attribute this treble
molestation of our cousin, the king's messenger?"

"True—adieu."

"Adieu, sirs, with many fair thanks for this good service."

They separated, and Balquhan rode on, feeling in his heart that he could
slay all who bore the name of Hamilton; for the idea that Redhall was his
evil genius never once occurred to him.

Those Leslies who had saved him were, nine years after, among the
conspirators who slew the great cardinal in his castle at St. Andrew's, less to
avenge the frightful deaths of the early martyrs, than as the hired assassins
of Henry VIII.; and twenty years after, the fiery Master of Rothes died in
the battle of St. Quentin, fighting valiantly at the head of thirty Scottish
gens d'armes.

CHAPTER LIV.

THE KING'S HORN.


"Be yet advised, nor urge me to an outrage;
Thy power is lost—unhand me."
Edward the Black Prince.

The clock of St. Leonard's tower struck three as Leslie entered the old
burgh of Kinghorn, and rode through its steep and straggling, narrow and
deserted wynds, to the hostelry with which the reader is already acquainted.
Though a vast sheet of pale light was spread across the east, sunrise was
nearly an hour distant, and the whole town was silent as some ruined city in
a desert; every door was closed, and not a single face appeared at the rusty
gratings of the street windows.

It was not until after much noise and vociferation with the drowsy
peddies and stable-boys that Leslie gained admittance to the inn-yard, and
from the yard obtained ingress to the mansion, where his whole aspect
excited fear and suspicion. His armour was dimmed by water and rusted
with dew, cut, hacked, and bloody; the straps were loose and torn; he was
feverish and excited; and there was a stern determination in his bearing, as
he carefully took his petronels from his saddle-bow, and, ordering the
attendants to look well to his horse against the time of the ferry-boat sailing,
entered the first empty chamber that offered itself.

He looked first to the pardon, which, notwithstanding his frequent


immersions, was dry and secure; he looked next to the wheel-locks of his
fire-arms, which he laid on his pillow ready for immediate service.
Thereafter, he examined his apartment. The window was two stories from
the ground, and a harrow-grating amply secured it. Like all others in that
age, the door was secured by a multiplicity of bars, all of which he shot into
their sockets; and thereafter piled behind them all the available furniture—a
great oak almrie, a meal-girnel, four chairs, and, lastly, the table.

He then took off his armour, and found that his clothing was almost dry.

"Come, 'tis well," thought he; "save three pricks and four scratches, I am
not a whit the worse, and have still six hours for sleeping and dreaming of
merry Marion."

And after assuring himself that he could not be taken in flank either by
trap-door or sliding-panels, this brave and wary soldier threw himself on the
bed, and behind his barricades slept soundly and securely.

The ferry-boat was to sail at ten in the forenoon.

Half-an-hour before that time Leslie awoke, and sprang up quite


refreshed. His first glance was at his barricade.

"Oho! I have been beset even here!" said he, on perceiving that the door
had been forced, and the heavy almrie and girnel pushed about three inches
inwards, by which the chairs had been overturned, thus baffling the assault,
as their fall had scared the intruders.

The sun was shining brightly on the river, and the merchants were
opening their booths and displaying their goods under the stone arcades of
the principal wynd.

"This devilish piece of paper is likely to cost me dear. I find I must still
be guarded," thought Leslie, as he minutely examined his iron trappings,
stuck his petronels in his belt, and, with his sheathed sword under his arm,
descended to the hall of the hostel and ordered breakfast, but without
mentioning the attempt which had too evidently been made to disturb his
privacy. Looking sharply around, he seated himself at the arched ingle,
where a comfortable fire was blazing, and above which appeared a rude
fresco painting, which represented St. Leonard, the patron of Kinghorn,
surrounded by a swarm of churubs in the forest of Limoges.

"Quick, old hag—my breakfast," said the traveller to the landlady; "let
your rascals look well to my horse, or look well to themselves if they fail."

The gudewife—a slipshod and sullen-looking crone, with a nose and


chin that were nearly meeting, a coif of the time of James III., and an
enormous bunch of keys—being a little scared by the stern and distrustful
aspect of Leslie, who sat down by the table with his helmet on, left a buxom
damsel to attend on him, and retired. The young soldier found that his
indignation could no way extend to her substitute; for her cheeks were
blooming and her eyes sparkling with health and good-humour; she wore a
very piquant, short linen jacket, short petticoat, and her brown hair tied up
in a blue silk snood, after the fashion of unmarried girls in Scotland.

A fowl, from among several that were roasting on the spit, cheese, cakes,
and honey, cold beef, eggs and bacon, with the addition of ale, formed then,
as now, the staples for breakfast, and while it was preparing, Leslie solaced
himself by whistling the March to Harlow, and by means of a piece of half-
burned wood, decorating with an enormous pair of moustaches each of the
fat little cherubim which surrounded the figure of St. Leonard; an
amusement which neither the gudewife nor the diminutive gudeman, whom
she seemed to rule with "a rod of iron," dared to interrupt.

"This is for thee, my rosy belle," said Leslie, kissing the plump cheek of
the waiting-maid, after breakfast, "together with this French crown; as for
the rascal, thy master, and the hag, thy mistress, let them rejoice that I have
not burned the house about their ears, were it but to smoke out certain
Hamiltons, who, I am assured, are within it. Thou hearest me, fellow?"
added Leslie, as he passed the landlord, who, sheepishly, and bonnet in
hand, was standing at the door of the house.

"I do, gude sir, but understand ye nocht."

"Nor do I you; but wherefore was my door forced last night—this


morning, I should say—eh, thou rascally Fifer?"
"I swear to ye, noble sir, that, under God, I ken nocht o't," replied the
poor man, with the utmost earnestness.

"It may be so, for I see that, in thine own house, thou art but Joan
Tamson's man, as the saw has it."

The landlord gave a sickly smile.

"Harkee, gudeman, is thy better-half a Hamilton?"

"To my sorrow, I ken she is, sir," sighed the hosteller, in a whisper; "for
never one of her name enters Fife, between the East and West Neuk,
without lying a week and mair at the King's Horn, and never a bodle will
she take for the lawing, for they are a' her cousins to the hundredth degree,
and will scarcely let me call my soul my ain."

"Then, which of her worthy cousins are here now?"

"Sir John Hamilton of Kincavil," replied the gudeman, setting his teeth
on edge.

"And his room?—"

"Was the next to yours."

"Hum! indeed; and this Sir John extends his patronage to you, gudeman
—eh?"

"He pays like a prince, to be sure; for he had a fancy for my gudewife in
her young days."

"He is a man of taste, Kincavil!" said Leslie, smiling; "but where is my


horse?"

"My son holds it at the gate."

"How, the devil! is that tall fellow thy son?"


"No," replied the little man, with a grin of bitterness; "he is the son of
my wife."

As Leslie slipped another crown into the hand of the host, and was
turning away, a tall, swaggering cavalier—the same whom Roland Vipont
had fought with and wounded near the Water Gate, as related in a preceding
chapter of this history—brushed past him somewhat unceremoniously.

"Sir John of Kincavil!" said Leslie, with angry surprise.

"Well, sir! at your service," replied the other, swelling up his rose-
coloured doublet, and resting his left hand in the bowl-hilt of his long
rapier, as he assumed a lofty attitude.

"Is this to be taken as an insult?"

"It is to be taken just as you please," replied the other, twirling his
moustache.

"Take care, sir. I am on the king's service."

"Does that entitle you to occupy the whole doorway of the King's
Horn?"

"We are not equally armed—you see my coat of mail."

"Oh, that matters little—behold!" said Kincavil, as he opened the collar


of his doublet, and displayed below it a mail shirt of exquisite
workmanship. "We are quite equal, my friend," he added, clapping Leslie
with easy familiarity on the shoulder, while a number of armed men, who,
by their badges, seemed to be his followers, crowded ominously round
them.

"Kincavil!" said Leslie, scornfully, "the next time thou touchest me, pray
do so with a hand that is gloved."

"A thousand pardons," sneered Kincavil, whose insolence was as


proverbial as his deadly skill and admirable swordmanship, "I forgot thou
wert Falkland bred."
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like