Download Full Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications 1st Edition Anghel Leonard PDF All Chapters
Download Full Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications 1st Edition Anghel Leonard PDF All Chapters
com
https://textbookfull.com/product/spring-boot-persistence-
best-practices-optimize-java-persistence-performance-in-
spring-boot-applications-1st-edition-anghel-leonard/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/pro-spring-security-securing-spring-
framework-5-and-boot-2-based-java-applications-2nd-edition-carlo-
scarioni/
textboxfull.com
https://textbookfull.com/product/spring-boot-up-and-running-building-
cloud-native-java-and-kotlin-applications-mark-heckler/
textboxfull.com
Cloud Native Java Designing Resilient Systems with Spring
Boot Spring Cloud and Cloud Foundry 1st Edition Long
https://textbookfull.com/product/cloud-native-java-designing-
resilient-systems-with-spring-boot-spring-cloud-and-cloud-foundry-1st-
edition-long/
textboxfull.com
https://textbookfull.com/product/spring-persistence-with-hibernate-
fisher-paul-murphy-brian-d/
textboxfull.com
Spring Boot
Persistence
Best Practices
Optimize Java Persistence Performance
in Spring Boot Applications
—
Anghel Leonard
www.allitebooks.com
Spring Boot Persistence
Best Practices
Optimize Java Persistence
Performance in Spring Boot
Applications
Anghel Leonard
www.allitebooks.com
Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in
Spring Boot Applications
Anghel Leonard
Banesti, Romania
www.allitebooks.com
This book is dedicated to my dear wife, Octavia.
www.allitebooks.com
Table of Contents
About the Author��������������������������������������������������������������������������������������������������xxiii
Chapter 1: Associations�������������������������������������������������������������������������������������������� 1
Item 1: How to Effectively Shape the @OneToMany Association�������������������������������������������������� 1
Always Cascade from Parent-Side to Child-Side�������������������������������������������������������������������� 2
Don’t Forget to Set mappedBy on the Parent-Side������������������������������������������������������������������ 2
Set orphanRemoval on the Parent-Side���������������������������������������������������������������������������������� 3
Keep Both Sides of the Association in Sync���������������������������������������������������������������������������� 3
Override equals( ) and hashCode( )����������������������������������������������������������������������������������������� 4
Use Lazy Fetching on Both Sides of the Association��������������������������������������������������������������� 5
Pay Attention to How toString( ) Is Overridden������������������������������������������������������������������������ 5
Use @JoinColumn to Specify the Join Column Name������������������������������������������������������������� 5
Author and Book Samples������������������������������������������������������������������������������������������������������� 6
Item 2: Why You Should Avoid the Unidirectional @OneToMany Association�������������������������������� 8
Regular Unidirectional @OneToMany������������������������������������������������������������������������������������ 10
Using @OrderColumn������������������������������������������������������������������������������������������������������������ 15
Using @JoinColumn�������������������������������������������������������������������������������������������������������������� 19
Item 3: How Efficient Is the Unidirectional @ManyToOne����������������������������������������������������������� 22
Adding a New Book to a Certain Author�������������������������������������������������������������������������������� 24
Fetching All Books of an Author��������������������������������������������������������������������������������������������� 26
Paging the Books of an Author���������������������������������������������������������������������������������������������� 27
Fetching All Books of an Author and Adding a New Book������������������������������������������������������ 28
Fetching all Books of an Author and Deleting a Book������������������������������������������������������������ 29
www.allitebooks.com
Table of Contents
vi
Table of Contents
Chapter 2: Entities�������������������������������������������������������������������������������������������������� 91
Item 13: How to Adopt a Fluent API Style in Entities������������������������������������������������������������������� 91
Fluent-Style via Entity Setters����������������������������������������������������������������������������������������������� 92
Fluent-Style via Additional Methods�������������������������������������������������������������������������������������� 95
Item 14: How to Populate a Child-Side Parent Association via a Hibernate-Specific Proxy�������� 98
Using findById( )�������������������������������������������������������������������������������������������������������������������� 99
Using getOne( )�������������������������������������������������������������������������������������������������������������������� 100
Item 15: How to Use Java 8 Optional in Persistence Layer������������������������������������������������������� 101
Optional in Entities�������������������������������������������������������������������������������������������������������������� 101
Optional in Repositories������������������������������������������������������������������������������������������������������ 103
Item 16: How to Write Immutable Entities��������������������������������������������������������������������������������� 104
Item 17: How to Clone Entities�������������������������������������������������������������������������������������������������� 106
Cloning the Parent and Associating the Books�������������������������������������������������������������������� 107
Cloning the Parent and the Books��������������������������������������������������������������������������������������� 110
Joining These Cases������������������������������������������������������������������������������������������������������������ 113
Item 18: Why and How to Activate Dirty Tracking���������������������������������������������������������������������� 114
Item 19: How to Map a Boolean to a Yes/No����������������������������������������������������������������������������� 117
Item 20: The Best Way to Publish Domain Events from Aggregate Roots��������������������������������� 119
Synchronous Execution������������������������������������������������������������������������������������������������������� 123
Asynchronous Execution����������������������������������������������������������������������������������������������������� 129
vii
Table of Contents
Item 29: Why to Pay Attention to Spring Projections that Include Associated Collections�������� 195
Using Nested Spring Closed Projection������������������������������������������������������������������������������� 195
Using a Simple Closed Projection���������������������������������������������������������������������������������������� 206
Transform List<Object[ ]> in DTO���������������������������������������������������������������������������������������� 208
Item 30: How to Fetch All Entity Attributes via Spring Projection���������������������������������������������� 213
Using the Query Builder Mechanism����������������������������������������������������������������������������������� 215
Using JPQL and @Query������������������������������������������������������������������������������������������������������ 215
Using JPQL with an Explicit List of Columns and @Query��������������������������������������������������� 217
Using a Native Query and @Query�������������������������������������������������������������������������������������� 218
Item 31: How to Fetch DTO via Constructor Expression������������������������������������������������������������ 219
Item 32: Why You Should Avoid Fetching Entities in DTO via the Constructor Expression�������� 223
Item 33: How to Fetch DTO via a JPA Tuple������������������������������������������������������������������������������� 226
Item 34: How to Fetch DTO via @SqlResultSetMapping and @NamedNativeQuery����������������� 229
Scalar Mappings������������������������������������������������������������������������������������������������������������������ 230
Constructor Mapping����������������������������������������������������������������������������������������������������������� 231
Entity Mapping��������������������������������������������������������������������������������������������������������������������� 233
Item 35: How to Fetch DTO via ResultTransformer������������������������������������������������������������������� 233
Item 36: How to Fetch DTO via a custom ResultTransformer���������������������������������������������������� 238
Item 37: How to Map an Entity to a Query via @Subselect������������������������������������������������������� 243
Item 38: How to Fetch DTO via Blaze-Persistence Entity Views������������������������������������������������ 247
Item 39: How to Effectively Fetch Parent and Association in One SELECT�������������������������������� 251
Item 40: How to Decide Between JOIN and JOIN FETCH����������������������������������������������������������� 256
Fetch All Authors and Their Books that Are More Expensive than the Given Price�������������� 257
How JOIN FETCH Will Act����������������������������������������������������������������������������������������������������� 258
How JOIN Will Act���������������������������������������������������������������������������������������������������������������� 259
Fetch All Books and their Authors��������������������������������������������������������������������������������������� 261
How JOIN FETCH Will Act����������������������������������������������������������������������������������������������������� 262
How JOIN Will Act���������������������������������������������������������������������������������������������������������������� 263
Item 41: How to Fetch All Left Entities�������������������������������������������������������������������������������������� 265
Item 42: How to Fetch DTO from Unrelated Entities������������������������������������������������������������������ 267
ix
Table of Contents
x
Table of Contents
xi
Table of Contents
xii
Table of Contents
Item 68: How to Correctly Override equals( ) and hashCode( )������������������������������������������������� 448
Building the Unit Test����������������������������������������������������������������������������������������������������������� 448
Best Approaches for Overriding equals( ) and hashCode( )������������������������������������������������� 451
Approaches for Overriding equals( ) and hashCode( ) that Must Be Avoided���������������������� 458
Item 69: How to Use Hibernate-Specific @NaturalId in Spring Style���������������������������������������� 463
Testing Time������������������������������������������������������������������������������������������������������������������������ 467
Compound Natural ID���������������������������������������������������������������������������������������������������������� 468
Item 70: How to Use Hibernate-Specific @NaturalId and Skip the Entity
Identifier Retrieval��������������������������������������������������������������������������������������������������������������������� 471
Using @NaturalIdCache Solely�������������������������������������������������������������������������������������������� 472
Using @NaturalIdCache and @Cache���������������������������������������������������������������������������������� 474
Item 71: How to Define an Association that References a @NaturalId Column������������������������ 477
Testing Time������������������������������������������������������������������������������������������������������������������������ 478
Item 72: How to Obtain Auto-Generated Keys��������������������������������������������������������������������������� 479
Retrieve Auto-Generated Keys via getId( )��������������������������������������������������������������������������� 480
Retrieve Auto-Generated Keys via JdbcTemplate���������������������������������������������������������������� 480
Retrieve Auto-Generated Keys via SimpleJdbcInsert���������������������������������������������������������� 482
Item 73: How to Generate Custom Sequence IDs��������������������������������������������������������������������� 482
Item 74: How to Efficiently Implement a Composite Primary Key��������������������������������������������� 484
Composite key via @Embeddable and @EmbeddedId�������������������������������������������������������� 486
Composite key via @IdClass����������������������������������������������������������������������������������������������� 497
How About the Universally Unique Identifier (UUID)?���������������������������������������������������������� 498
Generate UUID via GenerationType.AUTO����������������������������������������������������������������������������� 499
Manually Assigned UUID������������������������������������������������������������������������������������������������������ 501
Hibernate-Specific uuid2����������������������������������������������������������������������������������������������������� 502
Item 75: How to Define a Relationship in a Composite Key������������������������������������������������������ 503
Testing Time������������������������������������������������������������������������������������������������������������������������ 508
Persist a Publisher��������������������������������������������������������������������������������������������������������������� 508
Persist Two Authors������������������������������������������������������������������������������������������������������������� 509
Find an Author by Name������������������������������������������������������������������������������������������������������ 512
xiii
Table of Contents
xv
Table of Contents
xvi
Table of Contents
xvii
Table of Contents
Item 121: How to Implement Advanced Search via Specification API��������������������������������������� 757
Testing Time������������������������������������������������������������������������������������������������������������������������ 761
What’s Next������������������������������������������������������������������������������������������������������������������������� 763
Item 122: How to Enhance SQL Statement Caching via IN Clause Parameter Padding������������ 763
Item 123: How to Create Specification Query Fetch Joins�������������������������������������������������������� 767
Join Fetch and Pagination in Memory��������������������������������������������������������������������������������� 767
Join Fetch and Pagination in Database������������������������������������������������������������������������������� 769
Item 124: How to Use a Hibernate-Specific Query Plan Cache������������������������������������������������� 772
Item 125: How to Check if a Transient Entity Exists in the Database via Spring Query
By Example (QBE)���������������������������������������������������������������������������������������������������������������������� 774
Head-to-Head Comparison of All Attributes������������������������������������������������������������������������� 776
Head-to-Head Comparison of Certain Attributes����������������������������������������������������������������� 777
Apply the or Conjunction to a Subset of Attributes�������������������������������������������������������������� 778
Item 126: How to Include in the UPDATE Statement Only the Modified Columns via
Hibernate @DynamicUpdate����������������������������������������������������������������������������������������������������� 779
Item 127: How to Use Named (Native) Queries in Spring���������������������������������������������������������� 781
Referencing a Named (Native) Query���������������������������������������������������������������������������������� 782
Using @NamedQuery and @NamedNativeQuery���������������������������������������������������������������� 782
Using a Properties File ( jpa-named-queries.properties)����������������������������������������������������� 784
Item 128: The Best Way to Fetch Parent and Children in Different Queries/Requests�������������� 787
Item 129: How to Optimize the Merge Operation Using Update������������������������������������������������ 791
Item 130: How to Implement Concurrent Table Based Queues via the SKIP LOCKED Option���� 794
Set Up SKIP LOCKED������������������������������������������������������������������������������������������������������������ 795
Testing Time������������������������������������������������������������������������������������������������������������������������ 796
Item 131: How to Retry the Transaction After a Versioned (@Version)
OptimisticLockException����������������������������������������������������������������������������������������������������������� 798
Versioned Optimistic Locking Exception������������������������������������������������������������������������������ 799
Simulate an Optimistic Locking Exception�������������������������������������������������������������������������� 801
Retrying the Transaction������������������������������������������������������������������������������������������������������ 802
Testing Scenario������������������������������������������������������������������������������������������������������������������ 806
xviii
Table of Contents
Appendix C: Five SQL Performance Tips That Will Save Your Day������������������������ 937
Using SQL Functions in the WHERE Clause������������������������������������������������������������������������������� 937
The Index Column Order Matters���������������������������������������������������������������������������������������������� 938
Primary Key vs. Unique Key������������������������������������������������������������������������������������������������������ 939
LIKE vs. Equals (=)�������������������������������������������������������������������������������������������������������������������� 939
UNION vs. UNION ALL and JOIN Flavors������������������������������������������������������������������������������������ 941
xxi
Table of Contents
Index������������������������������������������������������������������������������������������������������������������� 1009
xxii
About the Author
Anghel Leonard is a Chief Technology Strategist and
independent consultant with 20+ years of experience in the
Java ecosystem. In his daily work, he focuses on architecting
and developing Java distributed applications that empower
robust architectures, clean code, and high-performance.
Anghel is also passionate about coaching, mentoring, and
technical leadership. He is the author of several books,
videos, and dozens of articles related to Java technologies.
xxiii
About the Technical Reviewer
Manuel Jordan Elera is an autodidactic developer and
researcher who enjoys learning new technologies for his
own experiments and creating new integrations. Manuel
won the Springy Award – Community Champion and Spring
Champion 2013. 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 for
Apress, including Pro Spring Boot 2 (2019), Rapid Java
Persistence and Microservices (2019), Java Language
Features (2018), Spring Boot 2 Recipes (2018), and Java APIs,
Extensions and Libraries (2018). Read his 13 detailed tutorials about many Spring
technologies, contact him through his blog at http://www.manueljordanelera.
blogspot.com, and follow him on his Twitter account, @dr_pompeii.
xxv
Introduction
In a nutshell, this book is a collection of best practices for Java persistence performance
in Spring Boot applications. These practices have been exposed via 120+ items, and they
can be grouped into three categories:
• Third, we deep dive into several Hibernate goodies that can sustain
the performance of your applications. By default, Spring Data relies
on Hibernate as its persistence provider, therefore you can exploit
Hibernate via Spring Data, and you can exploit underlying Hibernate
goodies as well. Goodies such as populating a child-side parent
association via a Hibernate proxy, using Dirty Tracking, delaying
connection acquisition, lazy loading attributes, and using natural
keys are just a few of the covered items.
The prerequisites of this book are pretty intuitive. You’ll need an IDE (e.g., NetBeans,
Eclipse, IntelliJ IDEA, Visual Studio, etc.), MySQL, and PostgreSQL. Optionally, you may
install or use other database vendors as well (e.g., Oracle, SQL Server, etc.).
xxvii
Introduction
For brevity’s sake and in order to avoid cluttering the climax of topics you
will see several shortcomings in code that should be avoided in production
as follows:
• hard-coded identifiers (primary keys) or other data that is a
good candidate for being arguments of metods
xxviii
Introduction
• Items: 6-9, 23, 24, 39-41, 43, 56, 66, 67, 81, 108
Fetch more data than needed
• Items: 10, 12, 21, 23-38, 42, 43, 45, 56, 57, 97, 98, 105, 128
Update/deletes huge lists of elements one-by-one
• Items: 46-55
Implement low-performing associations
• Items: 1-5, 11, 12, 14, 75, 76, 80
• Items: 61, 64
Don’t use @Transactional in an optimal way
• Items: 61-64
Don’t delay connection acquisition
• Items: 60, 64
Don’t use the most efficient queries (avoid window functions, CTE and native queries)
• Items: 10, 28-30, 34, 39, 41-45, 56, 59, 103, 105, 107, 108, 119-129
Don’t use smart entities
• Items: 10, 16, 18, 23, 35, 36, 37, 48, 60, 66, 67, 69-71, 77-80, 89-91, 103,
109, 111, 115, 124, 126, 132, 143-147
Use low-performing events and callbacks
• Items: 131-137
Use low-performing inheritance
• Items: 138-142
Lack of skills in fundamental JPA, SQL, flush, transactions, indexes, Second Level Cache
• Appendices: A-K
xxx
CHAPTER 1
Associations
Item 1: How to Effectively
Shape the @OneToMany Association
The bidirectional @OneToMany association is probably the most encountered association
in our Domain Model. Based on this statement, this book takes advantage of this
association in a significant number of examples.
Consider two entities, Author and Book, involved in a bidirectional lazy @OneToMany
association. In Figure 1-1, you can see the corresponding @OneToMany table relationship.
So, the author table has a @OneToMany relationship with the book table. An author row
can be referenced by multiple book rows. The author_id column maps this relationship
via a foreign key that references the primary key of the author table. A book cannot exist
without an author, therefore, the author is the parent-side (@OneToMany) while the book is
the child-side (@ManyToOne). The @ManyToOne association is responsible for synchronizing
the foreign key column with the Persistence Context (the First Level Cache).
1
© Anghel Leonard 2020
A. Leonard, Spring Boot Persistence Best Practices, https://doi.org/10.1007/978-1-4842-5626-8_1
Discovering Diverse Content Through
Random Scribd Documents
with fever—a boy of seven—and growing daily worse, so that when
we at last reached Tientsin he had a temperature of 107°.
When we approached the province of Shansi we got into a hilly
district, and crossed several ridges called “the Heavenly Gates.” In
some cases the ascent was pretty steep (2860 feet), and there were
temples at the bottom where the coolies prayed for a safe journey
up. When I stopped to sketch it aroused much interest, and
spectators always treated me with respect. It was explained to them
that I desired to show my mother the beauties of their country, so I
became the type of English “filial piety”!
The dangers of the road are numerous, and crossing the rivers is
often a very perilous proceeding: sometimes it is possible to ford
them, but the river-beds are so changeable that it was usually
necessary to have the guidance of experienced men. Sometimes we
had to be carried across on men’s backs, and it is not altogether a
pleasant experience to cling on to a bare, greasy back in a kneeling
position, with your arms round a most unwashed neck! Sometimes
we were ferried over, which was much the safest and pleasantest
way of crossing, and the charge is infinitesimally small.
Another danger of the road arises from the nature of the soil,
which is largely a loess formation. The road runs through deep
gulleys, often over 100 feet deep and quite narrow, but the loess
walls are apt to give way, especially after rain. One day we were
walking quietly along under a high cliff, when a deafening
thunderclap close behind us made us start and look back, to see a
dense cloud of dust where the cliff had fallen right across the path
we had just traversed. We had a very close shave that time. About a
year later my cousin was killed by the similar breaking down of a
road alongside a river; she was riding in a cart, and was buried
under it in the river. A friend who was with her had just got out to
walk a little, and consequently escaped.
During the rains travellers are often drowned by the sudden rush
of water down the gullies, and there are places of refuge in the high
banks—little caves or hollows. In some of the villages where we had
to stop the night the houses were dug in these cliffs, and were really
caves. The smells were atrocious, as there was but little ventilation.
The chimneys form danger traps to the unwary traveller walking
along the top of the cliffs; he may easily step into one, if he is not
looking carefully where he is going.
The day before we reached Tai Yuänfu, the capital of Shansi, we
stopped at a mission station in the charge of a delightful, courtly old
Chinese evangelist, whose hospitality I enjoyed several times. He
treated us royally, cooking dinner for us in European style, and
would have been sorely grieved had we offered him any
remuneration. When the troubles came later, not only he but every
member of his little flock—forty-one in all—were “faithful unto
death,” refusing to accept life at the price of recantation.
The journey from the coast took altogether a fortnight, and I
was glad when at last we reached the wide plain in which Tai Yuänfu
is situated. In May it is a vision of loveliness with its crops of millet,
sorghum, and poppy—white and puce colour—but now it was one
monotonous expanse of dust. The dust storms which blow across
the plain are terribly trying; they are as bewildering and as blinding
as a fog, and they sometimes go on daily for weeks during the early
part of the year.
Shansi is one of the worst provinces of all as regards opium-
smoking, and the poppy is largely cultivated. In the accompanying
sketch a group of patients is seen, who have come to a mission
refuge to try and break off the habit. They are allowed to smoke
tobacco, but are mostly resting or sleeping on the khang; the brick
bed seen in every inn and in most private houses. On the floor in
front of it is seen a small round aperture, where the fire is fed, which
heats the whole khang. The present Governor of Shansi is taking
active steps to put down opium cultivation, and the prospect seems
hopeful. Revenons à nos moutons. When we reached the city gate
there was a slight delay, as carts are apt to get jammed in it.
Though the gateway is large it is considerably blocked by stones, set
up by a former governor to prevent carts of above a certain gauge
from entering the city: this was to encourage the trade of the
wheelwrights. Now there is a railway right up to the walls of the city,
but from what I have already said it will be easily understood how
difficult a task it has been to construct a safe line. The railway joins
the Péhan line at Cheng Ting.
OPIUM REFUGE
CHAPTER X
Taiyüanfu
T
AIYÜAN is surrounded by a lofty wall, with a gateway at each
of the four points of the compass. The Chinese always use
these terms when we should use “right” and “left”: they speak
of the position of furniture in a room, for instance, as being north,
south, east, or west, and can always tell you the relative positions of
places and things in that way. It is the seat of the Government of the
province, and was the first place in the Empire to have a Western
university after the 1900 troubles.
The finest of all its temples—whether Confucian, Buddhist,
Mohammedan, or Taoist—is the temple of Heaven and Hell. The
entrance is magnificent in colouring, with roof and walls covered
with turquoise-coloured tiles peculiar to this province, which make its
temples so much more beautiful than those in the west. There are
interesting but repulsive statues within, mostly depicting the
torments of hell. In one temple, however, there is a deity to which
childless women especially come to pray. She is a hideous figure
about life size, with a gaping mouth, into which they stuff raw eggs
by way of offering. On the adjoining wall is a fresco representing
people receiving babies out of a cash-bag full of them, which a man
carries over his shoulder.
I visited the temple at the time of a large fair, which was held in
its courtyards (a common custom in China), and had one of the
teachers in attendance, to his great disgust, as it is not the correct
thing for Chinese ladies to go to fairs, and European manners had
not yet penetrated to this part of the Empire. It was a very fine
sight, notwithstanding the absence of the élite, for the women and
children were most gaily attired—and then the setting! They were all
perfectly civil to us and ready to talk. A woman was feeding her five-
year-old baby, not yet weaned. Family parties kept arriving on
donkeys, and women had their feet tied up in bags to protect their
dainty shoes from the dust of the road. At one side theatricals were
going on, to a loud and ceaseless accompaniment of drums. The
theatres are all connected with the temples, a visible sign of their
origin in the East as well as in the West; and the theatre and temple
dues are collected together. Actors are looked down on, and none is
allowed to compete in the literary examinations; they are in the
lowest grade of society. The accompanying sketch gives some idea
of the beautiful colour scheme of temple and theatre eaves. It is the
open-air stage of a theatre at Showyang, about sixty miles from
Taiyüan. The little figures of beasts on the roof are a characteristic
feature.
THEATRE STAGE
The stalls were full of interesting objects from all parts of the
province, and we went round buying various things that took our
fancy. There were handsome embroideries and lovely silks, and I
was surprised to find that we could take whatever we liked without
paying for it; it was sufficient to say, “Come to the mission hospital
to-morrow and the doctor will pay.” No Chinaman could have had
better credit, and few, I think, as good, in this city.
From the temple of Heaven and Hell we returned past the
barracks, and saw the men practising walking on stilts; apparently
that was part of their drill, as finally they all filed off into the yard on
them. The soldiers are quite a decent set of men, and one of the
officers frequently sent them to the hospital to be broken of the
opium habit. It is terribly common here. In a neighbouring town it is
estimated that 90 per cent. of the population (men, women, and
children) are smokers.
From Taiyüanfu we made an interesting little excursion to a
place to the south-west called Tsinssu, where there is a magnificent
old temple on the rocky hillside dominating the village. The temple is
overshadowed by hoary trees, and has remarkable golden dragons
twisted round the pillars of the façade. In the grounds are hot
springs, and the water flows under an ornamental bridge leading to
the terrace on which the temple stands. Had it not been for the hot
water it would have been impossible to sketch, as the water froze on
the surface of the paper, and every few minutes I had to put my
paint-box in the stream to thaw the coating of ice formed on the
colours. The subject, however, was so charming that I could not
waste the one chance I had of sketching, and in the afternoon I
made a rapid drawing of a pagoda, with the little bells hung on each
story tinkling in the breeze; an adjacent tower looked precisely like
an English church, but its real use was as a granary. The hot springs
are valuable in enabling the people to grow rice, which is not grown
elsewhere so far north, and it is the motive-power of many paper-
mills in the district. In a recent expedition roe-deer, leopards, boars,
and David squirrels have been found in this neighbourhood, but we
saw nothing more interesting than a beautiful pastoral scene—a
shepherd lad piping a melancholy ditty to his sheep under the clear
blue sky. I should like to have sketched him, but the shadows were
already lengthening, and we had to hasten our return before the city
gates were closed.
PAGODA
We attended a review one day, and saw the old régime in its full
glory, now already a thing of the past. We started at 7 a.m. in the
cart, and although the parade-ground was only a quarter of a mile
away we were none too early. The soldiers were already mustered,
and two gorgeously arrayed officials were seated in state under a
canopy waiting for the Governor, with a fine sort of helmet on a
stand behind them. He arrived shortly after we did, and although
there was a drizzling rain the numberless banners looked lovely,
bowing down while the Governor passed, and then floating proudly
up again. Many of them were pale-blue silk and carried on long
bamboo rods. There were a good many soldiers mounted on smart
ponies that scampered along bravely; but the black turbans
surmounting the blue or red uniforms made them look rather like
women. Some of them were armed with bows and arrows, slung on
their backs; others had prehistoric guns which required two men to
work them, one to hold and the other to fire off by means of a
lighted stick of incense, which at other times was thrust (lighted)
into the soldier’s chest, where also he carried his powder!
One regiment was a great contrast to the others—the celebrated
tiger braves. They were clad cap-à-pie in yellow cloth striped with
black, even the boots and cap being of the same material. The latter
was most cunningly made, with little pink-lined ears which stood
erect, and ferocious black eyes, and white fangs, and a red tongue
hanging out. This alarming costume was supposed to render all
further equipment unnecessary, and I asked one of the “braves” if
he had no weapon, on which he showed me merely an ordinary
knife stuck in his waistband. I asked if he would sell me his uniform,
but as he could not do that he lent it, and I had an exact copy
made. On my return home Mr. Chamberlain saw it, and was struck
with the idea that the braves scared away the enemy by their
uniform and their roaring, and made a telling use of it later on in
describing the tactics of “the opposition”!
Yet a step farther back in history, it is interesting to learn how
the soldiers used to travel in earlier times. A model has recently
been constructed (by Professor Hopkinson) of the chariot used to
convey eighteen soldiers. This chariot was in use about a thousand
years ago in China, and registered distance, a gong sounding at the
end of every “li” (about one-third of a mile), and a bell at the end of
every ten “li.” This vehicle was called the “measure-mile drum
carriage,” and it is from the description of the mechanism given in
the writings of the period that the professor has made his model. An
ode was written in its honour. The chariot was drawn by four horses.
TIGER BRAVE
The main features of the review were the sword exercises,
varied with turning somersaults, the charging of soldiers with two-
pronged pikes, accompanied by roaring—and various feats of
horsemanship. The men rode about clinging to their horses from
underneath, or jumped on them going at full gallop. The review
lasted all day, and we got tired long before it was over. The military
examinations of officers were on the old lines, and success in getting
promotion depended on the strength shown in drawing a bow, or
lifting a weight. Two officers came to hospital for treatment on
account of having overstrained themselves by their exertions, and
were anxious lest they should be disqualified in consequence. Now
everything is changed. There are military colleges springing up,
where everything is modelled on the military systems of the West,
and students go in increasing numbers to Europe to study these at
first hand. The Ministry of War has decided to adopt the same
gradations of rank as those of the British army and navy
respectively; thus a second lieutenant in the navy will be of equal
rank with a senior lieutenant in the army, and so on. In the past,
military service was one of the two only ways in which it was
possible in China to climb the social ladder.
In September 1904 I saw one of the last great triennial
examinations, to which students came from all parts of the province.
It opened with a great procession, headed by the Governor and
examiners who had come from Peking. Some of the big men rode in
chairs, preceded by scarlet umbrellas, and boys carrying boards
enjoining silence, many banners and discordant drums. It seemed as
if all the rag-tag and bobtail of the city had been collected to grace
the occasion; they were decked out in magenta felt hats and scarlet
cloaks which by no means covered their rags and dirt. Some wore
scarlet and gilt, others green and gilt caps, but no shoes on their
feet. The three principal men were carried on chairs, raised on little
platforms and covered with yellow rugs, supposed to represent the
imperial dragon. The imperial letters were carried (wrapped in yellow
cloth) across the shoulders of men on horseback, and the imperial
seals under gay canopies. The examination buildings are extensive,
and are well seen from the city wall. There are 10,000 cells,
arranged in rows of 100 each in alleys closed by a door. Each cell is
about 6 feet high, 4 feet wide, and 5 feet deep, and is provided with
a sliding seat and a board for writing on, which the student can slide
into the same groove as the seat to curl up on at night, for he has to
spend three days and nights without leaving it. The cell is open in
front, and an invigilator walks up and down to see that no cheating
goes on. If the student is taken ill he may not leave, and if he dies
(not an infrequent occurrence at examination times) his body is
simply put over the wall at the outside end of the alley. These
examinations are competitive, and there may be only thirty or forty
vacancies for thousands of students. At Canton there are 25,000
cells in the examination hall, and each province has its own
examination, to which students of other provinces may not come.
There are characters at the end of the rows of cells, drawn from one
of the classics, which are used as numerals, to distinguish the rows
from one another.
It is interesting to observe what supreme importance is attached
by the Chinese to learning and to morals. Learning is the main road
to eminence; the only other one—the military service—is quite
subsidiary. The highest grade of the people is the Sze, the scholar,
and from it all public servants are drawn. There is no bar to prevent
men of other grades passing into this class, provided they fit
themselves to do so and pass the necessary examinations. There are
six examinations possible.
OLD EXAMINATION BUILDINGS
W
E reached Peking after dark, which was fortunate, as the
glamour of all one’s youthful dreams was not at once
dispelled by being brought face to face with the prosaic
European Legations which lie just within the gates. At the railway
station, which is close to the great gate leading to the Summer
Palace, we emerged into a shouting, jostling Chinese crowd, and
were put into rickshas by the friends—Chinese and American—who
had come to meet us. Police were keeping order after a fashion most
necessary, for I saw a pushing fellow seize an unlucky man who was
having a dispute and fling his ricksha to the ground as if it were a
dirty rag. When we and our luggage had been safely packed into a
ricksha we were swiftly drawn over the most shocking roads,
through the great gloomy gates, into the city. Everywhere we
seemed surrounded by towering walls of vast thickness. Over the
chief gateway is a large temple containing the tutelary deities, which
may give some idea of this thickness. It rises tier above tier and is
painted a beautiful Venetian red, and the tiles are a bright blue-
green; the overhanging eaves are of carved woodwork, painted blue
and green and gold. Opposite this entrance is that of the imperial
palace, above which one sees its orange-coloured tiles. From the top
of the wall one gets a fine view of the long approach to the palace,
gateway beyond gateway, in true Chinese style, and stretching on
every side an endless vista of trees and roofs of the city. Formerly
this was a favourite point de vue for watching royalties when they
drove out, but now no one is allowed to do this, and notice is sent to
the various embassies requesting foreigners to stay indoors when
the royal family is taking an airing!
CITY WALL OF PEKING
From the great gate eastward, part of the wall was held during
the siege by the Americans, aided by twenty British and twenty
Russian soldiers. One morning they awoke to find that during the
night the Chinese had built a tower on it, of about twenty feet high,
overlooking them. All the next day they had to lie close under their
criss-cross defences, but it was clear that unless the tower were
seized the Chinese would soon be masters of the situation. Captain
Myers planned its capture, inviting volunteers to help him, and
naturally the twenty British soldiers responded promptly. It was
arranged that the Americans and British should get round it from the
outer side of the wall, and the Russians join them from the inner
side. When the time came for the plan to be carried out it was quite
successful, except for the fact that no Russians took part in it, and
that Captain Myers was severely wounded. As we stood listening to
the story from one of the besieged we saw a touching scene in the
American barracks below us. A man entered carrying home mails,
and shouted out the fact. In a moment men came flying from every
quarter of the hitherto empty yard with hands outstretched; one
could almost see the throb of delight with which the letters were
seized. But this was in time of peace, and we could but dimly realise
what far greater excitement was caused by the arrival of a
messenger from Tientsin during the siege, after the sickening
suspense of hope deferred. How deadly must have been the
disappointment when the brief message ran that help was coming,
but not a word as to when, merely the egoistic remark that in
Tientsin they also had been besieged!
My sketch is taken on the top of the wall, and shows the part
held by the Americans: it extends from the spot where I was
standing as far as the building over the great gate, and the
embassies are close below the wall on the right-hand side.
The accounts of the siege which we heard from all those who
had lived through it agreed in one respect—the singular
defencelessness of the besieged, and the ease with which they
might have been wiped out—leading one to conceive the probability
of what a Chinese resident told me, that their commander-in-chief
determined that this should not be done. The time that followed the
siege seems to have been really in many ways worse than the siege
itself for those who remained in Peking.
Far the most impressive monument here is the altar of Heaven,
which lies at a short distance outside the inner city in an ancient
park, surrounded by a high wall. Passing through a simple doorway,
you drive in your ricksha up an avenue of acacias for a short
distance till you come to another wall, and here you must get out
before entering the inner park. The trees were already beginning to
look autumnal (November) as we made our way across the coarse
grass into another high-walled enclosure, surrounded by a moat; we
had to knock for admittance to a large courtyard, where the Emperor
spends the night once a year before offering the great national
sacrifice to Heaven. All the roofs of the buildings round the courtyard
were of brilliant green tiles, and contrasted beautifully with the
marble terrace, balustrades, and bridges. From here the Emperor
goes at 5.30 a.m., accompanied by his courtiers, to the great marble
altar of Heaven, about one-fifth of a mile distant across the park.
Fine stone pylons lead to the altar, but the paths are overgrown with
grass, and there is a look of desolation brooding over the place. The
altar is a high circular platform of marble, with three short flights of
steps leading up from each of the four points of the compass. The
Emperor ascends these steps, accompanied by his courtiers, but only
those over seventy years of age may go up the top flight and remain
with him while he kneels in the centre, under the vault of Heaven, to
offer his sacrificial prayer. No spectator is ever allowed to be present.
At the foot of the steps the sacrifice is offered, but the Emperor is no
longer obliged to slay the bullock himself, as in the old days. This act
is delegated to a high official. The sacrificial beasts are reared and
kept in the surrounding park. Twelve bales of cloth are burnt in great
braziers as an offering to Heaven; they are placed at short distances
from one another, and each time there is a new emperor a new
brazier is erected. Everything is round, as being emblematic of
Heaven, while in the temple to Earth everything is square, because
the earth is supposed to be square, and in the latter the sacrifices
are buried instead of being burnt, so that they may go down instead
of up!
Close to the altar of Heaven is a small round enclosure
containing a temple roofed with gorgeous lapis-lazuli blue tiles, like
the adjoining temple of Heaven, which is erected on a marble
platform exactly similar to the altar of Heaven.
TEMPLE OF HEAVEN
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.
textbookfull.com