100% found this document useful (3 votes)
105 views

Download Full Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications 1st Edition Anghel Leonard PDF All Chapters

Best

Uploaded by

leeseminkap1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
105 views

Download Full Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications 1st Edition Anghel Leonard PDF All Chapters

Best

Uploaded by

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

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Spring Boot Persistence Best Practices: Optimize


Java Persistence Performance in Spring Boot
Applications 1st Edition Anghel Leonard

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

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Pro Spring Security: Securing Spring Framework 5 and Boot


2-based Java Applications 2nd Edition Carlo Scarioni

https://textbookfull.com/product/pro-spring-security-securing-spring-
framework-5-and-boot-2-based-java-applications-2nd-edition-carlo-
scarioni/
textboxfull.com

Spring Boot 2 0 Projects Build production grade reactive


applications and microservices with Spring Boot English
Edition Mohamed Shazin Sadakath
https://textbookfull.com/product/spring-boot-2-0-projects-build-
production-grade-reactive-applications-and-microservices-with-spring-
boot-english-edition-mohamed-shazin-sadakath/
textboxfull.com

Practical Microservices Architectural Patterns: Event-


Based Java Microservices with Spring Boot and Spring Cloud
Christudas
https://textbookfull.com/product/practical-microservices-
architectural-patterns-event-based-java-microservices-with-spring-
boot-and-spring-cloud-christudas/
textboxfull.com

Spring Boot: Up and Running: Building Cloud Native Java


and Kotlin Applications Mark Heckler

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

Practical Microservices Architectural Patterns - Event-


Based Java Microservices with Spring Boot and Spring Cloud
1st Edition Binildas Christudas
https://textbookfull.com/product/practical-microservices-
architectural-patterns-event-based-java-microservices-with-spring-
boot-and-spring-cloud-1st-edition-binildas-christudas/
textboxfull.com

Pro Spring Boot 2: An Authoritative Guide to Building


Microservices, Web and Enterprise Applications, and Best
Practices 2nd Edition Felipe Gutierrez
https://textbookfull.com/product/pro-spring-boot-2-an-authoritative-
guide-to-building-microservices-web-and-enterprise-applications-and-
best-practices-2nd-edition-felipe-gutierrez/
textboxfull.com

Pro Spring Boot 2 An Authoritative Guide to Building


Microservices Web and Enterprise Applications and Best
Practices Second Edition Felipe Gutierrez
https://textbookfull.com/product/pro-spring-boot-2-an-authoritative-
guide-to-building-microservices-web-and-enterprise-applications-and-
best-practices-second-edition-felipe-gutierrez/
textboxfull.com

Spring Persistence with Hibernate Fisher Paul Murphy Brian


D

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

ISBN-13 (pbk): 978-1-4842-5625-1 ISBN-13 (electronic): 978-1-4842-5626-8


https://doi.org/10.1007/978-1-4842-5626-8

Copyright © 2020 by Anghel Leonard


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: Matthew Moodie
Coordinating Editor: Mark Powers
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.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 email [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 via the book’s product page, located at www.apress.com/9781484256251. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper

www.allitebooks.com
This book is dedicated to my dear wife, Octavia.

www.allitebooks.com
Table of Contents
About the Author��������������������������������������������������������������������������������������������������xxiii

About the Technical Reviewer�������������������������������������������������������������������������������xxv


Introduction���������������������������������������������������������������������������������������������������������xxvii

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

Item 4: How to Effectively Shape the @ManyToMany Association���������������������������������������������� 30


Choose the Owner of the Relationship���������������������������������������������������������������������������������� 31
Always Use Set not List��������������������������������������������������������������������������������������������������������� 31
Keep Both Sides of the Association in Sync�������������������������������������������������������������������������� 31
Avoid CascadeType.ALL and CascadeType.REMOVE�������������������������������������������������������������� 31
Setting Up the Join Table������������������������������������������������������������������������������������������������������� 32
Using Lazy Fetching on Both Sides of the Association���������������������������������������������������������� 32
Override equals( ) and hashCode( )��������������������������������������������������������������������������������������� 32
Pay Attention to How toString( ) Is Overridden���������������������������������������������������������������������� 32
Author and Book Samples����������������������������������������������������������������������������������������������������� 32
Item 5: Why Set Is Better than List in @ManyToMany����������������������������������������������������������������� 36
Using List������������������������������������������������������������������������������������������������������������������������������� 36
Using Set������������������������������������������������������������������������������������������������������������������������������� 38
Item 6: Why and When to Avoid Removing Child Entities with CascadeType.Remove and
orphanRemoval=true������������������������������������������������������������������������������������������������������������������ 41
Deleting Authors that Are Already Loaded in the Persistence Context���������������������������������� 45
One Author Has Already Been Loaded in the Persistence Context���������������������������������������� 45
More Authors Have Been Loaded in the Persistence Context������������������������������������������������ 46
One Author and His Associated Books Have Been Loaded in the Persistence Context��������� 48
Deleting When the Author and Books that Should Be Deleted Are Not Loaded in the
Persistence Context��������������������������������������������������������������������������������������������������������������� 50
Item 7: How to Fetch Associations via JPA Entity Graphs����������������������������������������������������������� 52
Defining an Entity Graph via @NamedEntityGraph���������������������������������������������������������������� 53
Ad Hoc Entity Graphs������������������������������������������������������������������������������������������������������������� 59
Defining an Entity Graph via EntityManager�������������������������������������������������������������������������� 61
Item 8: How to Fetch Associations via Entity Sub-­Graphs���������������������������������������������������������� 62
Using @NamedEntityGraph and @NamedSubgraph������������������������������������������������������������� 64
Using the Dot Notation (.) in Ad Hoc Entity Graphs���������������������������������������������������������������� 67
Defining an Entity Sub-Graph via EntityManager������������������������������������������������������������������ 70

vi
Table of Contents

Item 9: How to Handle Entity Graphs and Basic Attributes��������������������������������������������������������� 70


Item 10: How to Filter Associations via a Hibernate-­Specific @Where Annotation��������������������� 75
Item 11: How to Optimize Unidirectional/Bidirectional @OneToOne via @MapsId��������������������� 79
Regular Unidirectional @OneToOne��������������������������������������������������������������������������������������� 79
Regular Bidirectional @OneToOne����������������������������������������������������������������������������������������� 82
@MapsId to the Rescue of @OneToOne�������������������������������������������������������������������������������� 84
Item 12: How to Validate that Only One Association Is Non-Null������������������������������������������������� 87
Testing Time�������������������������������������������������������������������������������������������������������������������������� 89

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

Chapter 3: Fetching���������������������������������������������������������������������������������������������� 135


Item 21: How to Use Direct Fetching����������������������������������������������������������������������������������������� 135
Direct Fetching via Spring Data������������������������������������������������������������������������������������������� 136
Fetching via EntityManager������������������������������������������������������������������������������������������������� 137
Fetching via Hibernate-Specific Session����������������������������������������������������������������������������� 137
Direct Fetching and Session-Level Repeatable-Reads�������������������������������������������������������� 139
Direct Fetching Multiple Entities by ID�������������������������������������������������������������������������������� 146
Item 22: Why Use Read-Only Entities Whenever You Plan to Propagate Changes
to the Database in a Future Persistence Context���������������������������������������������������������������������� 148
Load Author in Read-Write Mode���������������������������������������������������������������������������������������� 148
Load Author in Read-Only Mode������������������������������������������������������������������������������������������ 149
Update the Author���������������������������������������������������������������������������������������������������������������� 150
Item 23: How to Lazy Load the Entity Attributes via Hibernate Bytecode Enhancement���������� 151
Enabling Lazy Loading of Attributes������������������������������������������������������������������������������������ 152
Attribute Lazy Loading and N+1������������������������������������������������������������������������������������������ 155
Attribute Lazy Loading and Lazy Initialization Exceptions��������������������������������������������������� 157
Item 24: How to Lazy Load the Entity Attributes via Subentities����������������������������������������������� 163
Item 25: How to Fetch DTO via Spring Projections�������������������������������������������������������������������� 167
JPA Named (Native) Queries Can Be Combined with Spring Projections���������������������������� 172
Class-Based Projections������������������������������������������������������������������������������������������������������ 176
How to Reuse a Spring Projection��������������������������������������������������������������������������������������� 177
How to Use Dynamic Spring Projections����������������������������������������������������������������������������� 179
Item 26: How to Add an Entity in a Spring Projection���������������������������������������������������������������� 181
Materialized Association������������������������������������������������������������������������������������������������������ 181
Not Materialized Association����������������������������������������������������������������������������������������������� 182
Item 27: How to Enrich Spring Projections with Virtual Properties
That Are/Aren’t Part of Entities������������������������������������������������������������������������������������������������� 184
Item 28: How to Efficiently Fetch Spring Projection Including *-to-One Associations�������������� 186
Using Nested Closed Projections����������������������������������������������������������������������������������������� 187
Using a Simple Closed Projection���������������������������������������������������������������������������������������� 190
Using a Simple Open Projection������������������������������������������������������������������������������������������ 192
viii
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

Item 43: How to Write JOIN Statements������������������������������������������������������������������������������������ 268


INNER JOIN�������������������������������������������������������������������������������������������������������������������������� 270
LEFT JOIN���������������������������������������������������������������������������������������������������������������������������� 271
RIGHT JOIN�������������������������������������������������������������������������������������������������������������������������� 272
CROSS JOIN������������������������������������������������������������������������������������������������������������������������� 273
FULL JOIN���������������������������������������������������������������������������������������������������������������������������� 275
Simulate a FULL JOIN in MySQL������������������������������������������������������������������������������������������ 276
Item 44: How to Paginate JOINs������������������������������������������������������������������������������������������������ 277
The DENSE_RANK( ) Window Function to the Rescue��������������������������������������������������������� 283
Item 45: How to Stream the Result Set (in MySQL) and How to Use the Streamable Utility����� 287
Stream the Result Set (in MySQL)��������������������������������������������������������������������������������������� 287
Do Not Confuse Stream with the Streamable Utility������������������������������������������������������������ 288
Don’t Fetch More Columns than Needed Just to Drop a Part of them via map( )���������������� 290
Don’t Fetch More Rows than Needed Just to Drop a Part of Them via filter( )�������������������� 290
Pay Attention to Concatenating Streamable via and( )�������������������������������������������������������� 291
How to Return Custom Streamable Wrapper Types������������������������������������������������������������� 293

Chapter 4: Batching���������������������������������������������������������������������������������������������� 297


Item 46: How to Batch Inserts in Spring Boot Style������������������������������������������������������������������ 297
Enabling Batching and Preparing the JDBC URL����������������������������������������������������������������� 297
Preparing the Entities for Batching Inserts�������������������������������������������������������������������������� 300
Identify and Avoid the Built-In saveAll(Iterable<S> entities) Drawbacks���������������������������� 302
Custom Implementation Is the Way to Go���������������������������������������������������������������������������� 303
Testing Time������������������������������������������������������������������������������������������������������������������������ 307
Item 47: How to Optimize Batch Inserts of Parent-­Child Relationships������������������������������������ 309
Ordering Inserts������������������������������������������������������������������������������������������������������������������� 310
Item 48: How to Control Batch Size at the Session Level��������������������������������������������������������� 312
Item 49: How to Fork-Join JDBC Batching�������������������������������������������������������������������������������� 313
Fork-Join Batching�������������������������������������������������������������������������������������������������������������� 314
Item 50: Batching Entities via CompletableFuture�������������������������������������������������������������������� 318

x
Table of Contents

Item 51: How to Efficiently Batch Updates�������������������������������������������������������������������������������� 322


Versioned Entities���������������������������������������������������������������������������������������������������������������� 323
Batch Updates of Parent-Child Relationships���������������������������������������������������������������������� 323
Bulk Updates����������������������������������������������������������������������������������������������������������������������� 324
Item 52: How to Efficiently Batch Deletes (No Associations)���������������������������������������������������� 326
Delete via the Built-In deleteAllInBatch( ) Method��������������������������������������������������������������� 328
Delete via the Built-In deleteInBatch(Iterable<T> entities) ������������������������������������������������ 329
Delete via the Built-In deleteAll( ) Methods������������������������������������������������������������������������� 331
Delete via the Built-In delete(T entity) Method�������������������������������������������������������������������� 333
Item 53: How to Efficiently Batch Deletes (with Associations)�������������������������������������������������� 334
Relying on orphanRemoval = true��������������������������������������������������������������������������������������� 335
Delete via the Built-In deleteInBatch(Iterable<T> entities) ������������������������������������������������ 337
Delete via the Built-In deleteAll(Iterable<? extends T> entities) and
delete(T entity) Methods������������������������������������������������������������������������������������������������������ 338
Relying on SQL, ON DELETE CASCADE��������������������������������������������������������������������������������� 342
Delete via the Built-In deleteAllInBatch( ) Method��������������������������������������������������������������� 343
Delete via the Built-In deleteInBatch(Iterable<T> entities) ������������������������������������������������ 343
Delete via the Built-In deleteAll(Iterable<? extends T> entities) and
delete(T entity) Methods������������������������������������������������������������������������������������������������������ 344
Item 54: How to Fetch Association in Batches�������������������������������������������������������������������������� 346
@BatchSize at the Collection-Level������������������������������������������������������������������������������������ 346
@BatchSize at Class/Entity-Level��������������������������������������������������������������������������������������� 349
Item 55: Why to Avoid PostgreSQL (BIG)SERIAL in Batching Inserts via Hibernate������������������� 352
Optimize the Identifier-Fetching Process���������������������������������������������������������������������������� 353
Optimize Batching via reWriteBatchedInserts��������������������������������������������������������������������� 354

Chapter 5: Collections������������������������������������������������������������������������������������������ 357


Item 56: How to JOIN FETCH an @ElementCollection Collection���������������������������������������������� 357
Item 57: How to DTO an @ElementCollection��������������������������������������������������������������������������� 359
Item 58: Why and When to Use @OrderColumn with @ElementCollection������������������������������� 362
Optimizing @ElementCollection via @OrderColumn����������������������������������������������������������� 366

xi
Table of Contents

Item 59: How to Merge Entity Collections��������������������������������������������������������������������������������� 373


Merging the Detached Collection���������������������������������������������������������������������������������������� 377
Testing Time������������������������������������������������������������������������������������������������������������������������ 380

Chapter 6: Connections and Transactions������������������������������������������������������������ 383


Item 60: How to Delay Connection Acquisition Until It’s Really Needed������������������������������������ 383
Item 61: How @Transactional(readOnly=true) Really Works����������������������������������������������������� 386
Item 62: Why Spring Ignores @Transactional��������������������������������������������������������������������������� 396
Item 63: How to Set and Check that Transaction Timeout and Rollback at Expiration Work as
Expected����������������������������������������������������������������������������������������������������������������������������������� 400
Setting Transaction and Query Timeouts����������������������������������������������������������������������������� 403
Check That a Transaction Was Rolled Back������������������������������������������������������������������������� 404
Item 64: Why and How to Use @Transactional in a Repository Interface���������������������������������� 404
Does Query-methods listed in an interface repository run by default
in a transactional-context?�������������������������������������������������������������������������������������������������� 405
Okay, So All I Have to Do Is Add @Transactional at the Service-Method Level, Right?������� 410
But, Generally Speaking, Is this Approach Always Enough?������������������������������������������������ 414
I Know! Let’s Move @Transactional in the Repository Interface!���������������������������������������� 416
But What If I Want to Call More Query-Methods in the Service-­Method?
Do I Lose ACID?������������������������������������������������������������������������������������������������������������������� 417
So, If I Delay the Connection Acquisition then I Can Avoid @Transactional in
Repository Interfaces?�������������������������������������������������������������������������������������������������������� 422
Three Simple and Common Scenarios�������������������������������������������������������������������������������� 426

Chapter 7: Identifiers�������������������������������������������������������������������������������������������� 433


Item 65: Why to Avoid the Hibernate 5 AUTO Generator Type in MySQL������������������������������������ 433
Item 66: How to Optimize the Generation of Sequence Identifiers via the
hi/lo Algorithm��������������������������������������������������������������������������������������������������������������������������� 435
Dealing with External Systems�������������������������������������������������������������������������������������������� 440
Item 67: How to Optimize the Generation of Sequence Identifiers via Pooled (-lo)
Algorithms��������������������������������������������������������������������������������������������������������������������������������� 441
The Pooled Algorithm���������������������������������������������������������������������������������������������������������� 442
The Pooled-Lo Algorithm����������������������������������������������������������������������������������������������������� 445

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

Remove a Book of an Author����������������������������������������������������������������������������������������������� 513


Remove an Author��������������������������������������������������������������������������������������������������������������� 514
Item 76: How to Use an Entity for the Junction Table��������������������������������������������������������������� 516
Define a Composite Primary Key for the Junction Table����������������������������������������������������� 516
Define an Entity for the Junction Table�������������������������������������������������������������������������������� 518
Plug In the Author and Book������������������������������������������������������������������������������������������������ 520

Chapter 8: Calculating Properties������������������������������������������������������������������������� 523


Item 77: How to Map Calculated Non-Persistent Properties����������������������������������������������������� 523
JPA Quick Approach������������������������������������������������������������������������������������������������������������ 523
JPA @PostLoad������������������������������������������������������������������������������������������������������������������� 524
Hibernate-specific @Formula��������������������������������������������������������������������������������������������� 525
Item 78: How to Map Calculated Persistent Properties via @Generated���������������������������������� 526
Hibernate-Specific @Generated������������������������������������������������������������������������������������������ 527
Item 79: How to Use SQL Functions with Multiple Parameters in JPQL Queries���������������������� 531
Function in the SELECT Part������������������������������������������������������������������������������������������������ 532
Function in the WHERE Part������������������������������������������������������������������������������������������������� 534
Item 80: How to Map @ManyToOne Relationship to an SQL Query Via @JoinFormula������������� 536

Chapter 9: Monitoring������������������������������������������������������������������������������������������� 541


Item 81: Why and How to Count and Assert SQL Statements��������������������������������������������������� 541
Item 82: How to Log the Binding and Extracted Parameters of a Prepared Statement������������ 546
TRACE���������������������������������������������������������������������������������������������������������������������������������� 546
Log4j 2��������������������������������������������������������������������������������������������������������������������������������� 548
MySQL and profileSQL=true������������������������������������������������������������������������������������������������ 549
Item 83: How to Log Query Details�������������������������������������������������������������������������������������������� 549
Via DataSource-Proxy���������������������������������������������������������������������������������������������������������� 549
Via log4jdbc������������������������������������������������������������������������������������������������������������������������� 550
Via P6spy����������������������������������������������������������������������������������������������������������������������������� 551
Item 84: How to Log Slow Queries with Threshold������������������������������������������������������������������� 552
Item 85: Log Transactions and Query-Methods Details������������������������������������������������������������� 554
Log Transactions Details������������������������������������������������������������������������������������������������������ 554
xiv
Table of Contents

Take Control via Transaction Callbacks������������������������������������������������������������������������������� 554


Log Query-Methods Execution Time������������������������������������������������������������������������������������ 557

Chapter 10: Configuring DataSource and Connection Pool����������������������������������� 561


Item 86: How to Customize HikariCP Settings�������������������������������������������������������������������������� 561
Tuning HikariCP Parameters via application.properties������������������������������������������������������ 562
Tuning HikariCP Parameters via application.properties and DataSourceBuilder����������������� 563
Tuning HikariCP Parameters via DataSourceBuilder����������������������������������������������������������� 564
Tuning Other Connection Pools�������������������������������������������������������������������������������������������� 565
Item 87: How to Configure Two Data Sources with Two Connection Pools������������������������������� 566
Testing Time������������������������������������������������������������������������������������������������������������������������ 572

Chapter 11: Audit�������������������������������������������������������������������������������������������������� 575


Item 88: How to Track the Creation and Modification Times and Entity Users�������������������������� 575
Rely on Spring Data JPA Auditing���������������������������������������������������������������������������������������� 576
Relying on Hibernate Support���������������������������������������������������������������������������������������������� 579
The createdBy and lastModifiedBy Fields��������������������������������������������������������������������������� 580
Testing Time������������������������������������������������������������������������������������������������������������������������ 583
Item 89: How to Enable Hibernate-Specific Envers Auditing���������������������������������������������������� 584
Auditing Entities������������������������������������������������������������������������������������������������������������������ 585
Schema Generation������������������������������������������������������������������������������������������������������������� 586
Querying the Entity Snapshots�������������������������������������������������������������������������������������������� 588
Item 90: How to Inspect the Persistence Context��������������������������������������������������������������������� 591
Item 91: How to Extract Table Metadata����������������������������������������������������������������������������������� 596

Chapter 12: Schemas�������������������������������������������������������������������������������������������� 601


Item 92: How to Set Up Flyway in Spring Boot�������������������������������������������������������������������������� 601
Quickest Flyway Setup (MySQL and PostgreSQL)��������������������������������������������������������������� 601
Instruct Flyway to Create the Database������������������������������������������������������������������������������� 602
Set Up Flyway via @FlywayDataSource������������������������������������������������������������������������������ 605
Flyway and Multiple Schemas��������������������������������������������������������������������������������������������� 606
Item 93: How to Generate Two Databases via schema-*.sql and Match Entities to Them�������� 606

xv
Table of Contents

Chapter 13: Pagination����������������������������������������������������������������������������������������� 609


Item 94: When and Why Offset Pagination May Become a Performance Penalty��������������������� 609
Index Scan in Offset and Keyset������������������������������������������������������������������������������������������ 609
Offset Pagination Pros and Cons����������������������������������������������������������������������������������������� 610
Spring Boot Offset Pagination��������������������������������������������������������������������������������������������� 612
Item 95: How to Optimize Offset Pagination with COUNT(*) OVER and Page<entity/dto>�������� 619
COUNT(*) OVER( ) Windowed Aggregate������������������������������������������������������������������������������ 619
Item 96: How to Optimize Offset Pagination with SELECT COUNT subquery and
Page<entity/dto>���������������������������������������������������������������������������������������������������������������������� 628
SELECT COUNT Subquery���������������������������������������������������������������������������������������������������� 628
Item 97: How to Use JOIN FETCH and Pageable����������������������������������������������������������������������� 636
Item 98: How to Fix HHH000104����������������������������������������������������������������������������������������������� 640
Fetching Managed Entities�������������������������������������������������������������������������������������������������� 641
Item 99: How to Implement Slice<T> findAll( )������������������������������������������������������������������������� 651
Quick Implementation��������������������������������������������������������������������������������������������������������� 652
Implementation of Slice<T> findAll(Pageable pageable)���������������������������������������������������� 656
Item 100: How to Implement Keyset Pagination����������������������������������������������������������������������� 658
Item 101: How to Add a Next Page Button to Keyset Pagination���������������������������������������������� 662
Item 102: How to Implement Pagination via ROW_NUMBER( )������������������������������������������������� 665

Chapter 14: Queries���������������������������������������������������������������������������������������������� 667


Item 103: How to Optimize SELECT DISTINCT via Hibernate-Specific
HINT_PASS_DISTINCT_THROUGH��������������������������������������������������������������������������������������������� 667
Item 104: How to Set Up JPA Callbacks������������������������������������������������������������������������������������ 673
Separate Listener Class via @EntityListeners��������������������������������������������������������������������� 675
Item 105: How to Use Spring Data Query Builder to limit the Result Set Size and to
Count and Delete Derived Queries�������������������������������������������������������������������������������������������� 677
Limiting the Result Set Size������������������������������������������������������������������������������������������������ 677
Count and Delete Derived Queries��������������������������������������������������������������������������������������� 682
Item 106: Why You Should Avoid Time-Consuming Tasks in Post-Commits������������������������������ 683
Item 107: How to Avoid Redundant save( ) Calls����������������������������������������������������������������������� 685

xvi
Table of Contents

Item 108: Why and How to Prevent N+1 Issues������������������������������������������������������������������������ 687


Hibernate-Specific @Fetch(FetchMode.JOIN) and N+1������������������������������������������������������ 689
Item 109: How to Use Hibernate-Specific Soft Deletes Support����������������������������������������������� 694
Hibernate Soft Deletes�������������������������������������������������������������������������������������������������������� 696
Item 110: Why and How to Avoid the OSIV Anti-Pattern������������������������������������������������������������ 704
Hibernate5Module��������������������������������������������������������������������������������������������������������������� 708
Explicitly (Manually) Initializing the Unfetched Lazy Properties������������������������������������������ 711
How About the Hibernate-Specific hibernate.enable_lazy_load_no_trans������������������������� 713
Item 111: How to Store Date/Time in UTC Time Zone (MySQL)������������������������������������������������� 714
Item 112: How to Shuffle Small Result Sets via ORDER BY RAND( )����������������������������������������� 717
Item 113: How to Use Subqueries in the WHERE/HAVING Clause��������������������������������������������� 718
Item 114: How to Call a Stored Procedure�������������������������������������������������������������������������������� 722
Calling a Stored Procedure that Returns a Value (Scalar Data Types)��������������������������������� 723
Calling a Stored Procedure that Returns a Result Set��������������������������������������������������������� 725
Item 115: How to Unproxy a Proxy�������������������������������������������������������������������������������������������� 736
What Is a Proxy Object?������������������������������������������������������������������������������������������������������� 736
An Entity Object and a Proxy Object Are Not Equal�������������������������������������������������������������� 737
Unproxy a Proxy������������������������������������������������������������������������������������������������������������������� 739
An Entity Object and an Unproxied Object Are Equal����������������������������������������������������������� 740
Item 116: How to Map a Database View����������������������������������������������������������������������������������� 741
Item 117: How to Update a Database View������������������������������������������������������������������������������� 743
Trigger UPDATE Statements������������������������������������������������������������������������������������������������� 745
Trigger INSERT Statements������������������������������������������������������������������������������������������������� 746
Trigger DELETE Statements������������������������������������������������������������������������������������������������� 747
Item 118: Why and How to Use WITH CHECK OPTION��������������������������������������������������������������� 749
Item 119: How to Efficiently Assign a Database Temporary Ranking to Rows�������������������������� 751
Using the ORDER BY Clause in the Query and in the OVER Clause�������������������������������������� 753
Use Multiple Columns with the OVER Clause���������������������������������������������������������������������� 754
Item 120: How to Efficiently Find Top N Rows of Every Group�������������������������������������������������� 755

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

Item 132: How to Retry a Transaction After a Versionless OptimisticLockException���������������� 808


Versionless Optimistic Locking Exception��������������������������������������������������������������������������� 808
Simulate an Optimistic Locking Exception�������������������������������������������������������������������������� 809
Retrying the Transaction������������������������������������������������������������������������������������������������������ 810
Testing Scenario������������������������������������������������������������������������������������������������������������������ 810
Item 133: How to Handle Versioned Optimistic Locking and Detached Entities������������������������ 811
Item 134: How to Use the Optimistic Locking Mechanism and Detached
Entities in long HTTP Conversations����������������������������������������������������������������������������������������� 815
Testing Time������������������������������������������������������������������������������������������������������������������������ 820
Item 135: How to Increment the Version of the Locked Entity Even If this
Entity Was Not Modified������������������������������������������������������������������������������������������������������������ 822
OPTIMISTIC_FORCE_INCREMENT���������������������������������������������������������������������������������������� 822
PESSIMISTIC_FORCE_INCREMENT�������������������������������������������������������������������������������������� 828
Item 136: How PESSIMISTIC_READ/WRITE Works�������������������������������������������������������������������� 833
PESSIMISTIC_READ������������������������������������������������������������������������������������������������������������� 835
PESSIMISTIC_WRITE������������������������������������������������������������������������������������������������������������ 839
Item 137: How PESSIMISTIC_WRITE Works with UPDATE/INSERT and DELETE Operations������ 843
Trigger UPDATE�������������������������������������������������������������������������������������������������������������������� 843
Trigger DELETE�������������������������������������������������������������������������������������������������������������������� 846
Trigger INSERT��������������������������������������������������������������������������������������������������������������������� 849

Chapter 15: Inheritance���������������������������������������������������������������������������������������� 853


Item 138: How to Efficiently Use Single Table Inheritance�������������������������������������������������������� 853
Persisting Data�������������������������������������������������������������������������������������������������������������������� 855
Queries and Single Table Inheritance���������������������������������������������������������������������������������� 856
Subclasses Attributes Non-Nullability Issue������������������������������������������������������������������������ 862
Optimize Memory Footprint of the Discriminator Column��������������������������������������������������� 865
Item 139: How to Fetch Certain Subclasses from a SINGLE_TABLE Inheritance Hierarchy������ 867
Item 140: How to Efficiently Use Join Table Inheritance����������������������������������������������������������� 870
Persisting Data�������������������������������������������������������������������������������������������������������������������� 872
Queries and Join Table Inheritance������������������������������������������������������������������������������������� 874
How to Use JPA JOINED Inheritance Strategy and Strategy Design Patterns��������������������� 882
xix
Table of Contents

Item 141: How to Efficiently Use Table-Per-Class Inheritance�������������������������������������������������� 885


Persisting Data�������������������������������������������������������������������������������������������������������������������� 887
Queries and Class-Per-Table Inheritance���������������������������������������������������������������������������� 888
Item 142: How to Efficiently Use @MappedSuperclass������������������������������������������������������������ 896
Persisting Data�������������������������������������������������������������������������������������������������������������������� 898

Chapter 16: Types and Hibernate Types���������������������������������������������������������������� 903


Item 143: How to Deal with Hibernate and Unsupported Types via the Hibernate
Types Library����������������������������������������������������������������������������������������������������������������������������� 903
Item 144: How to Map CLOBs and BLOBs��������������������������������������������������������������������������������� 906
Ease of Use (Trade-Off with Performance)�������������������������������������������������������������������������� 906
Avoiding Performance Penalties (Trade-Off Is Ease of Use)������������������������������������������������ 908
Item 145: How to Efficiently Map a Java Enum to a Database�������������������������������������������������� 910
Mapping via EnumType.STRING������������������������������������������������������������������������������������������� 911
Mapping via EnumType.ORDINAL���������������������������������������������������������������������������������������� 911
Mapping an Enum to a Custom Representation������������������������������������������������������������������ 912
Mapping an Enum to a Database-Specific Enum Type (PostgreSQL)���������������������������������� 914
Item 146: How to Efficiently Map a JSON Java Object to a MySQL JSON Column�������������������� 916
Persisting an Author������������������������������������������������������������������������������������������������������������ 918
Fetching/Updating the Author���������������������������������������������������������������������������������������������� 918
Fetching the Author by Querying the JSON������������������������������������������������������������������������� 919
Item 147: How to Efficiently Map a JSON Java Object to a PostgreSQL JSON Column������������ 920
Persisting an Author������������������������������������������������������������������������������������������������������������ 922
Fetching/Updating the Author���������������������������������������������������������������������������������������������� 922
Fetching the Author by Querying the JSON������������������������������������������������������������������������� 923

Appendix A: (Hibernate) JPA Fundamentals��������������������������������������������������������� 925


What Is a Persistence Unit?������������������������������������������������������������������������������������������������������ 925
What Is an EntityManagerFactory?������������������������������������������������������������������������������������������� 926
What Is an EntityManager?������������������������������������������������������������������������������������������������������� 926
Entity State Transitions������������������������������������������������������������������������������������������������������������� 931

Appendix B: Associations Efficiency�������������������������������������������������������������������� 935


xx
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

Appendix D: How to Create Useful Database Indexes������������������������������������������� 943


JPA 2.1 @Index������������������������������������������������������������������������������������������������������������������������� 943
Don’t Guess the Indexes����������������������������������������������������������������������������������������������������������� 945
Prioritize the Most Used SQL Queries for Indexing������������������������������������������������������������������� 945
Important SQL Queries Deserve Indexes����������������������������������������������������������������������������������� 946
Avoid Sorting Operations by Indexing GROUP BY and ORDER BY���������������������������������������������� 946
Rely on Indexes for Uniqueness������������������������������������������������������������������������������������������������ 947
Rely on Indexes for Foreign Keys���������������������������������������������������������������������������������������������� 947
Add Columns for Index-Only Access����������������������������������������������������������������������������������������� 948
Avoid Bad Standards����������������������������������������������������������������������������������������������������������������� 949

Appendix E: SQL Phenomena�������������������������������������������������������������������������������� 951


Dirty Writes������������������������������������������������������������������������������������������������������������������������������� 951
Dirty Reads�������������������������������������������������������������������������������������������������������������������������������� 953
Non-Repeatable Reads������������������������������������������������������������������������������������������������������������� 954
Phantom Reads������������������������������������������������������������������������������������������������������������������������� 955
Read Skews������������������������������������������������������������������������������������������������������������������������������ 956
Write Skews������������������������������������������������������������������������������������������������������������������������������ 957
Lost Updates����������������������������������������������������������������������������������������������������������������������������� 958

Appendix F: Spring Transaction Isolation Level���������������������������������������������������� 961


@Transactional(isolation =Isolation.READ_UNCOMMITTED)����������������������������������������������������� 961
@Transactional(isolation =Isolation.READ_COMMITTED)��������������������������������������������������������� 963
@Transactional(isolation =Isolation.REPEATABLE_READ)��������������������������������������������������������� 964
@Transactional(isolation =Isolation.SERIALIZABLE)����������������������������������������������������������������� 965

xxi
Table of Contents

Appendix G: Spring Transaction Propagation������������������������������������������������������� 967


Propagation.REQUIRED������������������������������������������������������������������������������������������������������������� 967
Propagation.REQUIRES_NEW���������������������������������������������������������������������������������������������������� 970
Propagation.NESTED����������������������������������������������������������������������������������������������������������������� 973
Propagation.MANDATORY���������������������������������������������������������������������������������������������������������� 975
Propagation.NEVER������������������������������������������������������������������������������������������������������������������� 976
Propagation.NOT_SUPPORTED�������������������������������������������������������������������������������������������������� 978
Propagation.SUPPORTS������������������������������������������������������������������������������������������������������������� 980

Appendix H: Understanding the Flushing Mechanism������������������������������������������ 985


Strict Flush Order of Actions����������������������������������������������������������������������������������������������������� 986
Flush Before Executing a Data Query Language (DQL): SELECT Query������������������������������������� 987
Flush Before Transaction Commits������������������������������������������������������������������������������������������� 987
Automatic Flush Modes������������������������������������������������������������������������������������������������������������ 987
Let the Code Talk����������������������������������������������������������������������������������������������������������������������� 991
Global Flush Mode�������������������������������������������������������������������������������������������������������������������� 993
Session-Level Flush Mode�������������������������������������������������������������������������������������������������������� 996
Query-Level Flush Mode����������������������������������������������������������������������������������������������������������� 997

Appendix I: Second Level Cache��������������������������������������������������������������������������� 999


NONSTRICT_READ_WRITE������������������������������������������������������������������������������������������������������ 1000
READ_ONLY����������������������������������������������������������������������������������������������������������������������������� 1001
READ_WRITE��������������������������������������������������������������������������������������������������������������������������� 1001
TRANSACTIONAL��������������������������������������������������������������������������������������������������������������������� 1002
Query Cache���������������������������������������������������������������������������������������������������������������������������� 1003

Appendix J: Tools����������������������������������������������������������������������������������������������� 1005

Appendix K: Hibernate 6������������������������������������������������������������������������������������� 1007

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:

• First, we discuss the best practices for defining entities, mapping


relationships, writing queries, fetching data, choosing identifiers
generators, and so on. Mainly, we cover the areas where Spring Boot
cannot help you with built-in artifacts and where you can avoid
important performance penalties that are hard to fix and may require
significant changes in your domain model.

• Second, we address best practices for using Spring Boot support


(more precisely, Spring Data). As you will see, relying on built-in
support as a silver bullet can come with performance penalties. For
example, using the Open Session in View, offset pagination, post-­
commits hooks, or misunderstanding @Transactional are just a few
of the covered topics. I’m pretty sure that you are ready and impatient
to jump into this category of items.

• 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

As you will see, I prefer to add @Repository annotation at repository


interface level. Is well-known that @Repository is useful for translating the
unchecked SQL specific exception to Spring exceptions. This way, we have to
handle only DataAccessException (and its subclasses).
Nevertheless, this is a valid statement in general when we use Spring, but
Spring Data repositories are already backed by a Spring proxy. In other
words, using @Repository doesn’t make any difference. I prefer to use it for
avoiding any confusions and simpy highlight the repository interfaces, but if
you consider this too verbose or just noise then feel free to remove it.

In an overwhelming percentage the examples used in this book uses


Hibernate JPA. In other words, we boostrap Hibernate as the JPA
provider which is the most common use case in Spring Boot applications
that uses Spring Data JPA. If your Sping Boot (Spring) application
boostraps Hibernate nativelly (e.g., via SessionFactoryBuilder,
BootstrapServiceRegistryBuilder, SessionRegistry,
Configuration, HibernateTransactionManager, etc.) then, depending
on the case/scenario, you may notice different behaviors.
In this book, when you encounter “Hibernate-specific” or “Hibernate ORM”
then I refer to something that doesn’t exist in JPA (exist only in Hibernate) and
it might not be that obvious in the corresponding context.

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

• usage of orElseThrow() for unwrapping Optional objects


(I prefer this approach because it quicky signals if is something
wrong with finding/loading the requested data)
• maybe something else that I forgot to mention here

Main performance penalties


Use eager fetching

• Items: 1-5, 7, 8, 9, 23, 24


Don’t prevent/fix N+1 issues

• 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: 6, 51-53, 59, 109, 126, 129


Use entities for read-only operations

• Items: 16, 22, 25-38, 42, 43, 56, 57, 95, 96


Implement low-performing batching

• Items: 46-55
Implement low-performing associations
• Items: 1-5, 11, 12, 14, 75, 76, 80

Use Open Session in View

• Items: 23, 110


Use low-performing identifiers

• Items: 55, 65-76


Use low-performing pagination

• Items: 44, 94-102


xxix
Introduction

Avoid using @Transactional for read-only queries

• 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: 13, 15-17, 19


Don’t exploit Hibernate goodies

• 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: 20, 104, 106


Don’t monitor and audit

• Items: 81-85, 88-91


Don’t exploit database capabilities
• Items: 112, 114, 116-120, 130
Perform faulty or low-performing settings

• Items: 86, 87, 92, 93


Avoid optimistic locking

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

For a supersonic guide to association efficiency, check out Appendix B.

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.

Figure 1-1. The @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

The first examination is held yearly by the district magistrate; it


lasts for three days, and the candidate has to write two essays, one
on poetry. The second examination is held (generally a few months
later) in a prefectural town, and is therefore called Fu Kau, or
country examination. The students who pass this examination are
called Shu Tsai. The third examination (only open to those who have
passed the previous one) is the triennial one, which takes place in
the capital of each province, as above described, and is called the Ju
Jen degree. This time the candidate has to write several more
essays than for the Shu Tsai degree; the quality most valued in
these essays is skill in quotation, both as to the number of
quotations made from the classics and the way in which they are
combined—this might aptly be compared to a string of pearls. The
candidates who obtain the Ju Jen degree are alone eligible for the
degree of Tsin Sze. This fourth examination takes place triennially at
Peking. The candidate is confined for nine days in a small
compartment in the examination building. No matter how great the
discomfort of this confinement may be, he has to write nine essays.
I obtained the most fascinating little crib containing the whole
classics, not larger than one inch square, which would offer a severe
temptation under such circumstances to the most conscientious
student! If the candidate is successful with his nine essays he
receives the title of Tsin Sze, but if not, he may be appointed to a
clerkship of a more or less important nature, according to the merit
of his essays.
A yet higher degree may be obtained called the Tien Sze,
because it is held in one of the buildings of the Imperial Palace. The
student at the head of the list is called Cheong Yuan; the second is
Paun Yien; the third is called Tua Hwa, and the fourth Chuan Lo To.
Their official title, which is also given to other successful candidates
in this examination, is Han Lin Yuan Shu Chi Sze, and they are
obliged to study for the next three years at the Han Lin Yuan for the
next examination. The successful candidates are retained at the Han
Lin, and the unsuccessful ones receive posts of lesser importance,
such as magistracies and other civil appointments. They are
6
considered to have a first claim to all such appointments.
This old examination system is being replaced by one in which
Western subjects are to a large extent taking the place of the
classics. Since 1904 the degrees of the Ju Jen and Han Lin have
been granted in this way to students educated abroad and examined
on their return to China. At the present time there are about 300
Chinese students in England, studying mainly law, medicine,
engineering, and manufactures: some are still in public schools,
grammar schools, &c.; others are at the English or Scotch
universities.
SOUTHERN SERVANT SCHOLAR

In the accompanying sketch of a scholar, the gold square worn


on the chest and a corresponding one on the back are equivalent to
the hoods granted by our universities, and the different designs on
them indicate the kind of degree. Wives of scholars have also the
right to wear the same insignia as their husbands.
The city of Taiyüanfu as described in this chapter is already a
thing of the past. Now a railway comes to its very gates. New
European-looking buildings are springing up in every direction; the
streets are being widened and properly paved, officials drive about
in smart broughams, and there is a daily delivery of letters instead of
a private post once a fortnight.
I return to Tientsin and take up the thread of my narrative in
1907. No sooner had we arrived there than a Chinese friend, clad in
a beautiful maize-coloured silk gown, came to call. He had come
from Peking expressly to meet us, and escorted us there next day,
being an old friend of my Taiyüanfu days. We were seen off in the
Chinese railway (so much preferable to the German and Belgian
lines) next day by one of the directors, who had kindly ordered a
special reserved carriage for us. A few hours of pleasant travel, with
tea served on board, brought us to the special goal of our ambition
—Peking.
CHAPTER XI
Peking

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

There are two particularly fine Buddhist temples at Peking, one


outside and the other inside the walls, the former being a monastic
establishment and swarming with degraded-looking monks. It has
the imperial double-storied roofs of a noble orange colour, and it was
a picturesque sight to see the orange-robed monks trooping into the
courtyard to evening prayer. There were many young boys amongst
them, probably sent from Manchuria as a thank-offering for the
recovery of a father from severe illness, and consequently doomed
to a life of idleness and ignorance. The Buddhist monks are
notorious in this city for their low morals, and the signs of it are
unmistakably stamped upon their faces; they do no work of any
kind, and live upon the alms given by worshippers or which they
have begged, according to the rules of the order. It is comic to see
the Buddhist monks strutting along under huge orange umbrellas,
nose in air, followed by a servant carrying the compulsory begging
bowl! The head of the monastery is an incarnate Buddha. In the
chief temple of this monastery is a gigantic standing figure of
Buddha, and you can go up a staircase to inspect the head, which is
otherwise hardly visible in the gloom of the lofty building, whose
only light comes from the doorway. In the smaller buildings are
other Buddhas of various kinds, and the Bodhisattwa, the 1000-
handed goddess Kwanyin.
In the Lama temple, three miles outside the city, there are
figures of the goddess of mercy, beside the three seated Buddhas,
and she is to be found in many of the temples. She was originally a
man, but had the heart of a woman! Here we were dreadfully
pestered by dirty children, whom the priest tried ineffectually to
keep in order. Each courtyard we came to had to be unlocked, but
he always let them pass through with us, clamouring for money. The
great feature of the yellow temple is a marble monument to the
memory of a lama who came from Tibet and died of smallpox. It is
composed of white marble, and the centre has a fine series of
carvings round it illustrating scenes from the life of the Buddha.
Unfortunately, after the siege of Peking French soldiers were
quartered here, and they are said to have amused themselves by
knocking off the head of every single figure. The effect of the white
marble and gold in the midst of hoary cypresses is very fine. This is
7
where the Dalai Lama was lodged during his stay in Peking. It must
have been a picturesque scene on his arrival, when he entered the
sacred precincts, passing between two long rows of yellow-clad
monks. Would that we had been there to see it, instead of at such a
dreary season! We had come in the face of considerable difficulties,
but it was well worth while; the wind blowing when we started in
rickshas soon developed into a typical Chili dust-storm, and soon
after leaving the city the men declared they could go no further.
Having no other chance of visiting the place, we determined not to
be baulked and set out on foot. We struggled bravely forward
through stinging, blinding dust till we got under the lee of its high
wall. The return journey was not so bad, as the wind was behind us,
and we could enjoy watching other passengers whom we met in the
city lying as flat as they could in rickshas, and with handkerchiefs
spread over their faces. We were almost unrecognisable when we
got in, and it was a well-nigh hopeless task to get rid of the dust
from hair and clothes.
For once a Chinese cart seemed a desirable thing, and we were
glad to find one waiting to take us to a Chinese friend’s house,
where we were to spend the remainder of our time at Peking. The
streets are broad and fairly well policed, but their roughness is
extraordinary, and when you sit cross-legged in the place of honour
at the back of a springless cart you are tossed from side to side like
a ball, and your head bumped unmercifully, till you have learned how
to avoid it. You get much more exercise than if you walk; the only
compensation is that you know you are doing the correct thing. Our
host, who is a successful young doctor, explained that he was
obliged to go in a cart to visit high-class patients, instead of on his
bicycle, though it took up a great deal more time.
We were glad to have a Chinaman to take us shopping, for our
mouths watered to see the attractive things in the native shops. The
minute that a European enters, up go the prices to at least double, if
not treble; so we had an amusing but not very successful time in
them. Our kind host could not bear to see us being cheated, and it
was with the utmost difficulty that I persuaded him to get me a
black spotted leopard-skin coat lined with lovely blue silk, on which I
had set my heart, as the shopman refused to come down to what he
considered a reasonable price. He begged us to let him in future get
what we wanted and have the things brought to his house for
inspection: the main difficulty lay in the fact that we did not know
what we wanted, for the most part; but about one thing I had no
doubt, and that was specimens of the noted nail paintings. There
was only one celebrated artist, and he was about to retire to his
native province of Szechwan, but by great good luck we secured a
book containing nine paintings done with the finger-nail, and two
white silk scrolls. The designs are excellent, and it is difficult to see
any difference from that of a brush in execution. The book is bound
in Chinese style, simply between two wooden boards, with a plain
band of gold running down one side for about three-quarters of its
length, but no title on it.
A comparison between Chinese and Japanese art shows plainly
their close connection, and if the Japanese excel in certain qualities,
they have not the virility which characterises the Chinese, from
whom all their art is derived. It was towards the close of the fourth
century a.d. that a systematic criticism of art and a history of
painters was begun in China. The canons of pictorial art were laid
down, and it will help us to understand and appreciate Chinese art
better if we remember that the first and most important of their six
canons is “the Life movement of the Spirit through the Rhythm of
Things.” Though their art is mainly decorative, it possesses
marvellous vitality and poetic imagination. At the Chinese Court
there were fifteen artists in attendance, ready to depict anything
that the Dowager Empress might wish to have painted.
AN OFFICIAL A LADY OF QUALITY

A distinguished lady, closely allied to the Empress, kindly gave


me a sitting one morning; but as she was at the time exempted from
attendance at Court on account of ill-health, she was unable to wear
full dress—namely, the large Manchu coiffure—which is so heavy
that the Empress decided to allow it to be replaced by large black
satin bows. It is difficult to fasten the framework securely to the
head, over which the hair is arranged, so the coiffure is usually
made with false hair, and it is funny to see withered old hags in the
streets wearing these, with a large flower stuck jauntily at the side. I
found my sitter a very difficult one to paint, as she was heavily
painted (in a different sense), and the square scarlet under-lip and
absence of line in the upper eyelid gave a wooden expression to the
whole face, which was unusually large, and surmounted by a perfect
flower-bed. It would have been easier to express the dignity of her
carriage had she been standing, but although she offered to do so, I
felt it was impossible to take advantage of her good-nature when I
knew she was ill. Her hands were slender and beautifully shaped,
but she wore no rings; her feet were very small and shod in
artistically embroidered Manchu shoes with white soles—nearly two
inches thick (the Manchus never bind their feet). Unfortunately, the
handsome heliotrope gown and short jacket were trimmed with
European braid, and owing to the cold weather they were wadded,
which lends a clumsy appearance to the whole figure. Her charming
little black pug belongs to the celebrated palace breed.
It was not till after we had enjoyed tea and cakes that I was
allowed to begin the portrait; and the prince came in to make our
acquaintance, so that a good deal of time was taken up, and I was
only able to make a hasty sketch, to be finished later on. Then the
lady said we must certainly be hungry and insisted on our stopping
to dinner, saying she herself was very hungry—how much more so
must we be, who had worked while she did nothing. My friend
protested that she had done nothing at all, being reduced to silence
by her ignorance of the language, to which came the charming
retort, “You will be fatigued, then, by your good intentions!” All our
protests as to other engagements were overruled, and we sat down,
at the other end of the room from where we had been sitting before,
to a sumptuous repast, consisting of every kind of meat and
vegetable, served in small pieces in innumerable little dishes. In the
centre of the table there was a charming set of nine dishes, which
are generally used for sweetmeats, but which our hostess had
thought would be equally nice for meat—an innovation we
thoroughly appreciated, as they looked so much prettier than
separate ones. From these dishes we were continually helped to cold
chicken, duck, sausage, pigeons, eggs, ham, and other less
recognisable dainties. Round these were more dishes of hot
vegetables, pickled meat and vegetable, rissoles, fried meat balls,
stewed meat, cabbage and meat, &c., &c., from all of which our
hostess continued to serve us with her own chopsticks, eating but
little herself, according to the Chinese etiquette. We were given
spoons and forks, as she shrewdly suspected our inability to wield
chopsticks. Little bowls of rice were also handed round, and as soon
as we stopped eating she did the same. Next came bowls of soup,
each containing two eggs, and this concluded the solid part of the
feast; as soon as we had retired to the other end of the room tea
was brought, with preserved crab-apples, apple jam, and peanuts.
Part of the dinner, we were told, was prepared by men and part by
women cooks.
Before we took leave the children came in to be introduced. All
the young people are learning English, and shook hands in English
style—namely, with us, instead of with themselves. Many polite
questions were asked as to our families, our clothes, and the price of
the Viennese gown I was wearing, and my amethyst pendant. Silk is
considered the only material for a handsome dress in China, and
precious stones are practically unknown, jade being the only one
worn.
Finally we made our adieux, accompanied to the outermost
courtyard by our kind hostess; and the next day she sent me a
fascinating assortment of Chinese paints, each done up separately in
the neatest little parcel, containing either a bottle or a little box. We
came away much impressed by the indescribable charm of Chinese
manners, and many a time afterwards I felt how gauche we were in
comparison. We drove away in our cart for politeness’ sake, but a
short ride in it after such a feast would have had disastrous
consequences, so we quickly transferred ourselves to rickshas as
soon as we were out of sight of the palace.
It would be wearisome to the reader to describe all the
interesting places we saw in Peking, but there is still one that I must
mention—the Hall of the Classics. It is the centre of the great
examination system of the past, and probably will never again have
its old importance. Here the final examination took place of all the
students, from every part of the vast Empire, who had succeeded in
passing all other examinations. The Emperor himself presided, and
received the homage of successful candidates, seated upon a
handsome carved throne. Round the walls of the great court are
tablets on which are inscribed the whole of the classics. The old
examination system has been abolished, and already at Peking the
very building where the provincial examinations were held has been
destroyed.
Before leaving Peking our host introduced us to the friend whom
he had found to act as our interpreter during our long journey from
north-east to south-west of the Empire. Mr. Ku was a young man of
official family, who had been trained at St. John’s College, Shanghai,
and spoke English well. He was essentially a scholar, of gentle and
amiable manners, honourable and guileless. During our five months
together we never found him lacking in tact or discretion, and we
were able without hesitation to place our affairs entirely in his
hands. Fortunate is the traveller who likes his companions better at
the end of such a journey than at the beginning!
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!

textbookfull.com

You might also like