Spring Boot Persistence Best Practices (eBook)
XXX, 1027 Seiten
Apress (Verlag)
978-1-4842-5626-8 (ISBN)
This book is a collection of developer code recipes and best practices for persisting data using Spring, particularly Spring Boot. The book is structured around practical recipes, where each recipe discusses a performance case or performance-related case, and almost every recipe has one or more applications. Mainly, when we try to accomplish something (e.g., read some data from the database), there are several approaches to do it, and, in order to choose the best way, you have to know the implied trades-off from a performance perspective. You'll see that in the end, all these penalties slow down the application. Besides presenting the arguments that favor a certain choice, the application is written in Spring Boot style which is quite different than plain Hibernate.
Persistence is an important set of techniques and technologies for accessing and using data, and this book demonstrates that data is mobile regardless of specific applications and contexts. In Java development, persistence is a key factor in enterprise, ecommerce, cloud and other transaction-oriented applications.
After reading and using this book, you'll have the fundamentals to apply these persistence solutions into your own mission-critical enterprise Java applications that you build using Spring.
What You Will Learn
- Shape *-to-many associations for best performances
- Effectively exploit Spring Projections (DTO)
- Learn best practices for batching inserts, updates and deletes
- Effectively fetch parent and association in a single SELECT
- Learn how to inspect Persistent Context content
- Dissect pagination techniques (offset and keyset)
- Handle queries, locking, schemas, Hibernate types, and more
Who This Book Is For
Any Spring and Spring Boot developer that wants to squeeze the persistence layer performances.
Anghel Leonard is a Chief Technology Strategist with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
This book is a collection of developer code recipes and best practices for persisting data using Spring, particularly Spring Boot. The book is structured around practical recipes, where each recipe discusses a performance case or performance-related case, and almost every recipe has one or more applications. Mainly, when we try to accomplish something (e.g., read some data from the database), there are several approaches to do it, and, in order to choose the best way, you have to know the implied trades-off from a performance perspective. You'll see that in the end, all these penalties slow down the application. Besides presenting the arguments that favor a certain choice, the application is written in Spring Boot style which is quite different than plain Hibernate.Persistence is an important set of techniques and technologies for accessing and using data, and this book demonstrates that data is mobile regardless of specific applications and contexts. In Java development, persistence is a key factor in enterprise, ecommerce, cloud and other transaction-oriented applications. After reading and using this book, you'll have the fundamentals to apply these persistence solutions into your own mission-critical enterprise Java applications that you build using Spring.What You Will LearnShape *-to-many associations for best performancesEffectively exploit Spring Projections (DTO) Learn best practices for batching inserts, updates and deletes Effectively fetch parent and association in a single SELECTLearn how to inspect Persistent Context contentDissect pagination techniques (offset and keyset)Handle queries, locking, schemas, Hibernate types, and more Who This Book Is For Any Spring and Spring Boot developer that wants to squeeze the persistencelayer performances.
Table of Contents 5
About the Author 23
About the Technical Reviewer 24
Introduction 25
Chapter 1: Associations 29
Item 1: How to Effectively Shape the @OneToMany Association 29
Always Cascade from Parent-Side to Child-Side 30
Don’t Forget to Set mappedBy on the Parent-Side 30
Set orphanRemoval on the Parent-Side 31
Keep Both Sides of the Association in Sync 31
Override equals() and hashCode() 32
Use Lazy Fetching on Both Sides of the Association 33
Pay Attention to How toString() Is Overridden 33
Use @JoinColumn to Specify the Join Column Name 33
Author and Book Samples 34
Item 2: Why You Should Avoid the Unidirectional @OneToMany Association 36
Regular Unidirectional @OneToMany 38
Persisting an Author and Their Books 38
Persisting a New Book of an Existing Author 40
Deleting the Last book 41
Deleting the First Book 42
Using @OrderColumn 43
Persist the Author and Books 44
Persist a New Book of an Existing Author 45
Delete the Last Book 45
Delete the First Book 46
Using @JoinColumn 47
Persist the Author and Books 47
Persist a New Book of an Existing Author 48
Delete the Last Book 49
Delete the First Book 49
Item 3: How Efficient Is the Unidirectional @ManyToOne 50
Adding a New Book to a Certain Author 52
Fetching All Books of an Author 54
Paging the Books of an Author 55
Fetching All Books of an Author and Adding a New Book 56
Fetching all Books of an Author and Deleting a Book 57
Item 4: How to Effectively Shape the @ManyToMany Association 58
Choose the Owner of the Relationship 59
Always Use Set not List 59
Keep Both Sides of the Association in Sync 59
Avoid CascadeType.ALL and CascadeType.REMOVE 59
Setting Up the Join Table 60
Using Lazy Fetching on Both Sides of the Association 60
Override equals() and hashCode() 60
Pay Attention to How toString() Is Overridden 60
Author and Book Samples 60
Item 5: Why Set Is Better than List in @ManyToMany 64
Using List 64
Using Set 66
Preserving the Order of the Result Set 67
Using @OrderBy 68
Item 6: Why and When to Avoid Removing Child Entities with CascadeType.Remove and orphanRemoval=true 69
Deleting Authors that Are Already Loaded in the Persistence Context 73
One Author Has Already Been Loaded in the Persistence Context 73
More Authors Have Been Loaded in the Persistence Context 74
One Author and His Associated Books Have Been Loaded in the Persistence Context 76
Deleting When the Author and Books that Should Be Deleted Are Not Loaded in the Persistence Context 78
Item 7: How to Fetch Associations via JPA Entity Graphs 80
Defining an Entity Graph via @NamedEntityGraph 81
Overriding a Query Method 82
Using the Query Builder Mechanism 83
Using Specification 84
Using @Query and JPQL 85
Ad Hoc Entity Graphs 87
Defining an Entity Graph via EntityManager 89
Item 8: How to Fetch Associations via Entity Sub-Graphs 90
Using @NamedEntityGraph and @NamedSubgraph 92
Using the Dot Notation (.) in Ad Hoc Entity Graphs 95
Defining an Entity Sub-Graph via EntityManager 98
Item 9: How to Handle Entity Graphs and Basic Attributes 98
Item 10: How to Filter Associations via a Hibernate-Specific @Where Annotation 103
Item 11: How to Optimize Unidirectional/Bidirectional @OneToOne via @MapsId 107
Regular Unidirectional @OneToOne 107
Regular Bidirectional @OneToOne 110
@MapsId to the Rescue of @OneToOne 112
Item 12: How to Validate that Only One Association Is Non-Null 115
Testing Time 117
Chapter 2: Entities 119
Item 13: How to Adopt a Fluent API Style in Entities 119
Fluent-Style via Entity Setters 120
Fluent-Style via Additional Methods 123
Item 14: How to Populate a Child-Side Parent Association via a Hibernate-Specific Proxy 126
Using findById() 127
Using getOne() 128
Item 15: How to Use Java 8 Optional in Persistence Layer 129
Optional in Entities 129
Optional in Repositories 131
Item 16: How to Write Immutable Entities 132
Item 17: How to Clone Entities 134
Cloning the Parent and Associating the Books 135
Cloning the Parent and the Books 138
Joining These Cases 141
Item 18: Why and How to Activate Dirty Tracking 142
Item 19: How to Map a Boolean to a Yes/No 145
Item 20: The Best Way to Publish Domain Events from Aggregate Roots 147
Synchronous Execution 151
Asynchronous Execution 157
Chapter 3: Fetching 162
Item 21: How to Use Direct Fetching 162
Direct Fetching via Spring Data 163
Fetching via EntityManager 164
Fetching via Hibernate-Specific Session 164
Direct Fetching and Session-Level Repeatable-Reads 166
Direct Fetching Multiple Entities by ID 173
Item 22: Why Use Read-Only Entities Whenever You Plan to Propagate Changes to the Database in a Future Persistence Context 175
Load Author in Read-Write Mode 175
Load Author in Read-Only Mode 176
Update the Author 177
Item 23: How to Lazy Load the Entity Attributes via Hibernate Bytecode Enhancement 178
Enabling Lazy Loading of Attributes 179
Attribute Lazy Loading and N+1 182
Attribute Lazy Loading and Lazy Initialization Exceptions 184
Setting Explicit Default Values for Lazy Loaded Attributes 186
Providing a Custom Jackson Filter 187
Item 24: How to Lazy Load the Entity Attributes via Subentities 190
Item 25: How to Fetch DTO via Spring Projections 194
JPA Named (Native) Queries Can Be Combined with Spring Projections 199
Class-Based Projections 203
How to Reuse a Spring Projection 204
How to Use Dynamic Spring Projections 206
Item 26: How to Add an Entity in a Spring Projection 208
Materialized Association 208
Not Materialized Association 209
Item 27: How to Enrich Spring Projections with Virtual Properties That Are/Aren’t Part of Entities 211
Item 28: How to Efficiently Fetch Spring Projection Including *-to-One Associations 213
Using Nested Closed Projections 214
Using a Simple Closed Projection 217
Using a Simple Open Projection 219
Item 29: Why to Pay Attention to Spring Projections that Include Associated Collections 222
Using Nested Spring Closed Projection 222
Use the Query Builder Mechanism 223
Use an Explicit JPQL 226
Use JPA JOIN FETCH 229
Using a Simple Closed Projection 233
Transform List< Object[ ]>
Item 30: How to Fetch All Entity Attributes via Spring Projection 240
Using the Query Builder Mechanism 242
Using JPQL and @Query 242
Using JPQL with an Explicit List of Columns and @Query 244
Using a Native Query and @Query 245
Item 31: How to Fetch DTO via Constructor Expression 246
Item 32: Why You Should Avoid Fetching Entities in DTO via the Constructor Expression 250
Item 33: How to Fetch DTO via a JPA Tuple 253
Item 34: How to Fetch DTO via @SqlResultSetMapping and @NamedNativeQuery 256
Scalar Mappings 257
Constructor Mapping 258
Entity Mapping 260
Item 35: How to Fetch DTO via ResultTransformer 260
Item 36: How to Fetch DTO via a custom ResultTransformer 265
Item 37: How to Map an Entity to a Query via @Subselect 270
Item 38: How to Fetch DTO via Blaze-Persistence Entity Views 274
Item 39: How to Effectively Fetch Parent and Association in One SELECT 278
Item 40: How to Decide Between JOIN and JOIN FETCH 283
Fetch All Authors and Their Books that Are More Expensive than the Given Price 284
How JOIN FETCH Will Act 285
How JOIN Will Act 286
Fetch All Books and their Authors 288
How JOIN FETCH Will Act 289
How JOIN Will Act 290
Item 41: How to Fetch All Left Entities 292
Item 42: How to Fetch DTO from Unrelated Entities 294
Item 43: How to Write JOIN Statements 295
INNER JOIN 297
LEFT JOIN 298
RIGHT JOIN 299
CROSS JOIN 300
FULL JOIN 302
Simulate a FULL JOIN in MySQL 303
Item 44: How to Paginate JOINs 304
The DENSE_RANK() Window Function to the Rescue 310
Item 45: How to Stream the Result Set (in MySQL) and How to Use the Streamable Utility 314
Stream the Result Set (in MySQL) 314
Do Not Confuse Stream with the Streamable Utility 315
Don’t Fetch More Columns than Needed Just to Drop a Part of them via map() 317
Don’t Fetch More Rows than Needed Just to Drop a Part of Them via filter() 317
Pay Attention to Concatenating Streamable via and() 318
How to Return Custom Streamable Wrapper Types 320
Chapter 4: Batching 323
Item 46: How to Batch Inserts in Spring Boot Style 323
Enabling Batching and Preparing the JDBC URL 323
Setting the Batch Size 323
Batching Optimizations for MySQL 324
Preparing the Entities for Batching Inserts 326
Identify and Avoid the Built-In saveAll(Iterable< S>
Custom Implementation Is the Way to Go 329
Writing the BatchRepository Contract 330
Writing the BatchRepository Implementation 330
Setting BatchRepositoryImpl as the Base Class 333
Testing Time 333
Item 47: How to Optimize Batch Inserts of Parent-Child Relationships 335
Ordering Inserts 336
Item 48: How to Control Batch Size at the Session Level 338
Item 49: How to Fork-Join JDBC Batching 339
Fork-Join Batching 340
Item 50: Batching Entities via CompletableFuture 344
Item 51: How to Efficiently Batch Updates 348
Versioned Entities 349
Batch Updates of Parent-Child Relationships 349
Bulk Updates 350
Item 52: How to Efficiently Batch Deletes (No Associations) 352
Delete via the Built-In deleteAllInBatch() Method 354
Delete via the Built-In deleteInBatch(Iterable< T>
Delete via the Built-In deleteAll() Methods 357
Delete via the Built-In delete(T entity) Method 359
Item 53: How to Efficiently Batch Deletes (with Associations) 360
Relying on orphanRemoval = true 361
Delete via the Built-In deleteAllInBatch() Method 362
Delete via the Built-In deleteInBatch(Iterable< T>
Delete via the Built-In deleteAll(Iterable< T>
Relying on SQL, ON DELETE CASCADE 368
Delete via the Built-In deleteAllInBatch() Method 369
Delete via the Built-In deleteInBatch(Iterable< T>
Delete via the Built-In deleteAll(Iterable< T>
Item 54: How to Fetch Association in Batches 372
@BatchSize at the Collection-Level 372
@BatchSize at Class/Entity-Level 375
Item 55: Why to Avoid PostgreSQL (BIG)SERIAL in Batching Inserts via Hibernate 378
Optimize the Identifier-Fetching Process 379
Optimize Batching via reWriteBatchedInserts 380
Chapter 5: Collections 382
Item 56: How to JOIN FETCH an @ElementCollection Collection 382
Item 57: How to DTO an @ElementCollection 384
Item 58: Why and When to Use @OrderColumn with @ElementCollection 387
Optimizing @ElementCollection via @OrderColumn 391
Adding One Book to the Beginning of the Current Cart 392
Adding One Book to the End of the Current Cart 393
Adding One Book to the Middle of the Current Cart 394
Removing the First Book from the Current Cart 395
Removing the Last Book from the Current Cart 396
Removing One Book from the Middle of the Current Cart 396
Item 59: How to Merge Entity Collections 398
Merging the Detached Collection 402
Testing Time 405
Chapter 6: Connections and Transactions 407
Item 60: How to Delay Connection Acquisition Until It’s Really Needed 407
Item 61: How @Transactional(readOnly=true) Really Works 410
Item 62: Why Spring Ignores @Transactional 420
Item 63: How to Set and Check that Transaction Timeout and Rollback at Expiration Work as Expected 424
Setting Transaction and Query Timeouts 427
Check That a Transaction Was Rolled Back 428
Item 64: Why and How to Use @Transactional in a Repository Interface 428
Does Query-methods listed in an interface repository run by default in a transactional-context? 429
Okay, So All I Have to Do Is Add @Transactional at the Service-Method Level, Right? 434
But, Generally Speaking, Is this Approach Always Enough? 438
I Know! Let’s Move @Transactional in the Repository Interface! 440
But What If I Want to Call More Query-Methods in the Service-Method? Do I Lose ACID? 441
So, If I Delay the Connection Acquisition then I Can Avoid @Transactional in Repository Interfaces? 446
Case 1 447
Case 2 448
Three Simple and Common Scenarios 450
Roll Back a Service-Method at Exception Thrown by the Code that Doesn't Interact with the Database 450
Cascading and @Transactional 452
Select ? Modify ? Save and an Interleaved Long-Running Task 452
Chapter 7: Identifiers 457
Item 65: Why to Avoid the Hibernate 5 AUTO Generator Type in MySQL 457
Item 66: How to Optimize the Generation of Sequence Identifiers via the hi/lo Algorithm 459
Dealing with External Systems 464
Item 67: How to Optimize the Generation of Sequence Identifiers via Pooled (-lo) Algorithms 465
The Pooled Algorithm 466
Dealing with External Systems 468
The Pooled-Lo Algorithm 469
Dealing with External Systems 471
Item 68: How to Correctly Override equals() and hashCode() 472
Building the Unit Test 472
Best Approaches for Overriding equals() and hashCode() 475
Using a Business Key 475
Using @NaturalId 477
Manually Assigned Identifier 478
Database-Generated Identifiers 480
Approaches for Overriding equals() and hashCode() that Must Be Avoided 482
Default Implementation (JVM) 482
Database-Generated Identifiers 483
Lombok @EqualsAndHashCode 485
Item 69: How to Use Hibernate-Specific @NaturalId in Spring Style 487
Testing Time 491
Compound Natural ID 492
Item 70: How to Use Hibernate-Specific @NaturalId and Skip the Entity Identifier Retrieval 495
Using @NaturalIdCache Solely 496
Using @NaturalIdCache and @Cache 498
Item 71: How to Define an Association that References a @NaturalId Column 501
Testing Time 502
Item 72: How to Obtain Auto-Generated Keys 503
Retrieve Auto-Generated Keys via getId() 504
Retrieve Auto-Generated Keys via JdbcTemplate 504
Retrieve Auto-Generated Keys via SimpleJdbcInsert 506
Item 73: How to Generate Custom Sequence IDs 506
Item 74: How to Efficiently Implement a Composite Primary Key 508
Composite key via @Embeddable and @EmbeddedId 510
Testing Time 516
Persist an Author and Three Books 516
Find an Author by Name 518
Remove a Book of an Author 518
Remove an Author 520
Composite key via @IdClass 521
How About the Universally Unique Identifier (UUID)? 522
Generate UUID via GenerationType.AUTO 523
Manually Assigned UUID 525
Hibernate-Specific uuid2 526
Item 75: How to Define a Relationship in a Composite Key 527
Testing Time 532
Persist a Publisher 532
Persist Two Authors 533
Find an Author by Name 536
Remove a Book of an Author 537
Remove an Author 538
Item 76: How to Use an Entity for the Junction Table 540
Define a Composite Primary Key for the Junction Table 540
Define an Entity for the Junction Table 542
Plug In the Author and Book 544
Chapter 8: Calculating Properties 547
Item 77: How to Map Calculated Non-Persistent Properties 547
JPA Quick Approach 547
JPA @PostLoad 548
Hibernate-specific @Formula 549
Item 78: How to Map Calculated Persistent Properties via @Generated 550
Hibernate-Specific @Generated 551
Formula via columnDefinition Element 552
Formula via CREATE TABLE 553
Testing Time 554
Item 79: How to Use SQL Functions with Multiple Parameters in JPQL Queries 555
Function in the SELECT Part 556
Function in the WHERE Part 558
Item 80: How to Map @ManyToOne Relationship to an SQL Query Via @JoinFormula 560
Chapter 9: Monitoring 564
Item 81: Why and How to Count and Assert SQL Statements 564
Item 82: How to Log the Binding and Extracted Parameters of a Prepared Statement 569
TRACE 569
Log4j 2 571
MySQL and profileSQL=true 572
Item 83: How to Log Query Details 572
Via DataSource-Proxy 572
Via log4jdbc 573
Via P6spy 574
Item 84: How to Log Slow Queries with Threshold 575
Item 85: Log Transactions and Query-Methods Details 577
Log Transactions Details 577
Take Control via Transaction Callbacks 577
Log Query-Methods Execution Time 580
Chapter 10: Configuring DataSource and Connection Pool 583
Item 86: How to Customize HikariCP Settings 583
Tuning HikariCP Parameters via application.properties 584
Tuning HikariCP Parameters via application.properties and DataSourceBuilder 585
Tuning HikariCP Parameters via DataSourceBuilder 586
Tuning Other Connection Pools 587
Item 87: How to Configure Two Data Sources with Two Connection Pools 588
Testing Time 594
Chapter 11: Audit 596
Item 88: How to Track the Creation and Modification Times and Entity Users 596
Rely on Spring Data JPA Auditing 597
Relying on Hibernate Support 600
The created and lastModified Fields 600
The createdBy and lastModifiedBy Fields 601
Testing Time 604
Item 89: How to Enable Hibernate-Specific Envers Auditing 605
Auditing Entities 606
Schema Generation 607
Querying the Entity Snapshots 609
ValidityAuditStrategy Audit Logging Strategy 610
Item 90: How to Inspect the Persistence Context 612
Item 91: How to Extract Table Metadata 617
Chapter 12: Schemas 622
Item 92: How to Set Up Flyway in Spring Boot 622
Quickest Flyway Setup (MySQL and PostgreSQL) 622
Instruct Flyway to Create the Database 623
MySQL 624
PostgreSQL 624
Set Up Flyway via @FlywayDataSource 626
Flyway and Multiple Schemas 627
Item 93: How to Generate Two Databases via schema-*.sql and Match Entities to Them 627
Chapter 13: Pagination 630
Item 94: When and Why Offset Pagination May Become a Performance Penalty 630
Index Scan in Offset and Keyset 630
Offset Pagination Pros and Cons 631
Spring Boot Offset Pagination 633
Item 95: How to Optimize Offset Pagination with COUNT(*) OVER and Page< entity/dto>
COUNT(*) OVER( ) Windowed Aggregate 640
Pages as Page< dto>
Pages as Page< entity>
Use a Dedicated Property 645
Item 96: How to Optimize Offset Pagination with SELECT COUNT subquery and Page< entity/dto>
SELECT COUNT Subquery 649
Pages as Page< dto>
Pages as Page< entity >
Use an Extra Property 654
Item 97: How to Use JOIN FETCH and Pageable 657
Item 98: How to Fix HHH000104 661
Fetching Managed Entities 662
Fetching Page< Author>
Fetching Slice< Author>
Fetching List< Author>
Item 99: How to Implement Slice< T>
Quick Implementation 673
Fetching Slice< entity>
Fetching Slice< dto>
Implementation of Slice< T>
Item 100: How to Implement Keyset Pagination 679
Item 101: How to Add a Next Page Button to Keyset Pagination 683
Item 102: How to Implement Pagination via ROW_NUMBER( ) 686
Chapter 14: Queries 688
Item 103: How to Optimize SELECT DISTINCT via Hibernate-Specific HINT_PASS_DISTINCT_THROUGH 688
Item 104: How to Set Up JPA Callbacks 694
Separate Listener Class via @EntityListeners 696
Item 105: How to Use Spring Data Query Builder to limit the Result Set Size and to Count and Delete Derived Queries 698
Limiting the Result Set Size 698
Count and Delete Derived Queries 703
Derived Count Queries 703
Derived Delete Queries 703
Item 106: Why You Should Avoid Time-Consuming Tasks in Post-Commits 704
Item 107: How to Avoid Redundant save() Calls 706
Item 108: Why and How to Prevent N+1 Issues 708
Hibernate-Specific @Fetch(FetchMode.JOIN) and N+1 710
Using JOIN FETCH Instead of FetchMode.JOIN 713
Using Entity Graphs Instead of FetchMode.JOIN 714
Item 109: How to Use Hibernate-Specific Soft Deletes Support 715
Hibernate Soft Deletes 717
Testing Time 719
Deleting an Author 719
Deleting a Book 721
Restoring an Author 722
Restoring a Book 723
Useful Queries 723
Update the Deleted Property in the Current Persistence Context 724
Item 110: Why and How to Avoid the OSIV Anti-Pattern 725
Hibernate5Module 729
Testing Time 730
Explicitly (Manually) Initializing the Unfetched Lazy Properties 732
Testing Time 732
How About the Hibernate-Specific hibernate.enable_lazy_load_no_trans 734
Item 111: How to Store Date/Time in UTC Time Zone (MySQL) 735
Item 112: How to Shuffle Small Result Sets via ORDER BY RAND() 738
Item 113: How to Use Subqueries in the WHERE/HAVING Clause 739
Item 114: How to Call a Stored Procedure 743
Calling a Stored Procedure that Returns a Value (Scalar Data Types) 744
Calling a Stored Procedure that Returns a Result Set 746
Calling a Stored Procedure via JdbcTemplate 746
Call the Stored Procedure that Returns the Nickname and Age Columns of Authors of the Given Genre (Can Be One or Multiple Authors) 747
Call the Stored Procedure that Returns All Authors of the Given Genre 748
Calling a Stored Procedure via a Native Query 749
Call the Stored Procedure that Returns the Nickname and Age Columns of Authors of the Given Genre (Can Be One or Multiple Authors) 749
Call the Stored Procedure that Returns All Authors of the Given Genre 750
Calling a Stored Procedure via EntityManager 751
Call the Stored Procedure that Returns the Nickname and Age Columns of Authors of the Given Genre (Can Be One or Multiple Authors) 751
Call the Stored Procedure that Returns All Authors of the Given Genre 754
Item 115: How to Unproxy a Proxy 757
What Is a Proxy Object? 757
An Entity Object and a Proxy Object Are Not Equal 758
Unproxy a Proxy 760
An Entity Object and an Unproxied Object Are Equal 761
Item 116: How to Map a Database View 762
Item 117: How to Update a Database View 764
Trigger UPDATE Statements 766
Trigger INSERT Statements 767
Trigger DELETE Statements 768
Item 118: Why and How to Use WITH CHECK OPTION 770
Item 119: How to Efficiently Assign a Database Temporary Ranking to Rows 772
Using the ORDER BY Clause in the Query and in the OVER Clause 774
Use Multiple Columns with the OVER Clause 775
Item 120: How to Efficiently Find Top N Rows of Every Group 776
Item 121: How to Implement Advanced Search via Specification API 778
Testing Time 782
Fetch All Authors Older than 40 of Genre Anthology 782
Fetch a Page of Books with a Price Less than 60 783
What’s Next 784
Item 122: How to Enhance SQL Statement Caching via IN Clause Parameter Padding 784
Item 123: How to Create Specification Query Fetch Joins 788
Join Fetch and Pagination in Memory 788
Join Fetch and Pagination in Database 790
Item 124: How to Use a Hibernate-Specific Query Plan Cache 793
Item 125: How to Check if a Transient Entity Exists in the Database via Spring Query By Example (QBE) 795
Head-to-Head Comparison of All Attributes 797
Head-to-Head Comparison of Certain Attributes 798
Apply the or Conjunction to a Subset of Attributes 799
Item 126: How to Include in the UPDATE Statement Only the Modified Columns via Hibernate @DynamicUpdate 800
Item 127: How to Use Named (Native) Queries in Spring 802
Referencing a Named (Native) Query 803
Using @NamedQuery and @NamedNativeQuery 803
Using a Properties File ( jpa-named-queries.properties) 805
Item 128: The Best Way to Fetch Parent and Children in Different Queries/Requests 808
Item 129: How to Optimize the Merge Operation Using Update 812
Item 130: How to Implement Concurrent Table Based Queues via the SKIP LOCKED Option 815
Set Up SKIP LOCKED 816
Testing Time 817
Item 131: How to Retry the Transaction After a Versioned (@Version) OptimisticLockException 819
Versioned Optimistic Locking Exception 820
Simulate an Optimistic Locking Exception 822
Retrying the Transaction 823
Testing Scenario 827
Item 132: How to Retry a Transaction After a Versionless OptimisticLockException 829
Versionless Optimistic Locking Exception 829
Simulate an Optimistic Locking Exception 830
Retrying the Transaction 831
Testing Scenario 831
Item 133: How to Handle Versioned Optimistic Locking and Detached Entities 832
Item 134: How to Use the Optimistic Locking Mechanism and Detached Entities in long HTTP Conversations 836
Testing Time 841
Item 135: How to Increment the Version of the Locked Entity Even If this Entity Was Not Modified 843
OPTIMISTIC_FORCE_INCREMENT 843
PESSIMISTIC_FORCE_INCREMENT 849
Item 136: How PESSIMISTIC_READ/WRITE Works 854
PESSIMISTIC_READ 856
MySQL and MySQL5Dialect Dialects (MyISAM) 857
MySQL and MySQL5InnoDBDialect/ MySQL8Dialect Dialects (InnoDB) 858
PostgreSQL and PostgreSQL95Dialect 860
Other RDBMS 860
PESSIMISTIC_WRITE 860
MySQL and MySQL5Dialect dialect (MyISAM) 861
MySQL and MySQL5InnoDBDialect/ MySQL8Dialect Dialects (InnoDB) 862
PostgreSQL and PostgreSQL95Dialect 863
Other RDBMS 863
Item 137: How PESSIMISTIC_WRITE Works with UPDATE/INSERT and DELETE Operations 864
Trigger UPDATE 864
Trigger DELETE 867
Trigger INSERT 870
Trigger INSERT in MySQL with REPEATABLE_READ 872
Trigger INSERT in MySQL with READ_COMMITTED 873
Chapter 15: Inheritance 874
Item 138: How to Efficiently Use Single Table Inheritance 874
Persisting Data 876
Queries and Single Table Inheritance 877
Fetching the Books by Author Identifier 878
Fetching the Books by Title 878
Fetching the Paperbacks 880
Fetching the Author and the Associated Books 881
Subclasses Attributes Non-Nullability Issue 883
Optimize Memory Footprint of the Discriminator Column 886
Item 139: How to Fetch Certain Subclasses from a SINGLE_TABLE Inheritance Hierarchy 888
Item 140: How to Efficiently Use Join Table Inheritance 891
Persisting Data 893
Queries and Join Table Inheritance 895
Fetching the Books by Author Identifier 895
Fetching the Books by Title 896
Fetching the Paperbacks 897
Fetching the Author and the Associated Books 899
How to Use JPA JOINED Inheritance Strategy and Strategy Design Patterns 903
Item 141: How to Efficiently Use Table-Per-Class Inheritance 906
Persisting Data 908
Queries and Class-Per-Table Inheritance 909
Fetching the Books by Author Identifier 910
Fetching the Books by Title 911
Fetching the Paperbacks 912
Fetching the Author and the Associated Books 913
Item 142: How to Efficiently Use @MappedSuperclass 917
Persisting Data 919
Fetching the Paperbacks 920
Chapter 16: Types and Hibernate Types 923
Item 143: How to Deal with Hibernate and Unsupported Types via the Hibernate Types Library 923
Item 144: How to Map CLOBs and BLOBs 926
Ease of Use (Trade-Off with Performance) 926
Avoiding Performance Penalties (Trade-Off Is Ease of Use) 928
Item 145: How to Efficiently Map a Java Enum to a Database 930
Mapping via EnumType.STRING 931
Mapping via EnumType.ORDINAL 931
Mapping an Enum to a Custom Representation 932
Mapping an Enum to a Database-Specific Enum Type (PostgreSQL) 934
Writing a Custom Type 934
Using the Hibernate Types Library 935
Item 146: How to Efficiently Map a JSON Java Object to a MySQL JSON Column 936
Persisting an Author 938
Fetching/Updating the Author 938
Fetching the Author by Querying the JSON 939
Item 147: How to Efficiently Map a JSON Java Object to a PostgreSQL JSON Column 940
Persisting an Author 942
Fetching/Updating the Author 942
Fetching the Author by Querying the JSON 943
Appendix A: (Hibernate) JPA Fundamentals 945
What Is a Persistence Unit? 945
What Is an EntityManagerFactory? 946
What Is an EntityManager? 946
Entity State Transitions 951
Appendix B: Associations Efficiency 954
Appendix C: Five SQL Performance Tips That Will Save Your Day 955
Using SQL Functions in the WHERE Clause 955
The Index Column Order Matters 956
Primary Key vs. Unique Key 957
LIKE vs. Equals (=) 957
UNION vs. UNION ALL and JOIN Flavors 959
Appendix D: How to Create Useful Database Indexes 961
JPA 2.1 @Index 961
Don’t Guess the Indexes 963
Prioritize the Most Used SQL Queries for Indexing 963
Important SQL Queries Deserve Indexes 964
Avoid Sorting Operations by Indexing GROUP BY and ORDER BY 964
Rely on Indexes for Uniqueness 965
Rely on Indexes for Foreign Keys 965
Add Columns for Index-Only Access 966
Avoid Bad Standards 967
Appendix E: SQL Phenomena 968
Dirty Writes 968
Dirty Reads 970
Non-Repeatable Reads 971
Phantom Reads 972
Read Skews 973
Write Skews 974
Lost Updates 975
Appendix F: Spring Transaction Isolation Level 978
@Transactional(isolation =Isolation.READ_UNCOMMITTED) 978
@Transactional(isolation =Isolation.READ_COMMITTED) 980
@Transactional(isolation =Isolation.REPEATABLE_READ) 981
@Transactional(isolation =Isolation.SERIALIZABLE) 982
Appendix G: Spring Transaction Propagation 984
Propagation.REQUIRED 984
Propagation.REQUIRES_NEW 987
Propagation.NESTED 990
Propagation.MANDATORY 992
Propagation.NEVER 993
Propagation.NOT_SUPPORTED 995
Propagation.SUPPORTS 997
Appendix H: Understanding the Flushing Mechanism 1001
Strict Flush Order of Actions 1002
Flush Before Executing a Data Query Language (DQL): SELECT Query 1003
Flush Before Transaction Commits 1003
Automatic Flush Modes 1003
Let the Code Talk 1007
Global Flush Mode 1009
Session-Level Flush Mode 1012
Query-Level Flush Mode 1013
Appendix I: Second Level Cache 1015
NONSTRICT_READ_WRITE 1016
READ_ONLY 1017
READ_WRITE 1017
TRANSACTIONAL 1018
Query Cache 1019
Appendix J: Tools 1021
Appendix K: Hibernate 6 1023
Index 1025
Erscheint lt. Verlag | 29.4.2020 |
---|---|
Zusatzinfo | XXX, 1027 p. 148 illus., 143 illus. in color. |
Sprache | englisch |
Themenwelt | Mathematik / Informatik ► Informatik ► Programmiersprachen / -werkzeuge |
Schlagworte | ACCESS • Best Practices • Code • Cookbook • Data • Developer • Hibernate • Java • orm • Persistence • Recipes • source • Spring |
ISBN-10 | 1-4842-5626-3 / 1484256263 |
ISBN-13 | 978-1-4842-5626-8 / 9781484256268 |
Haben Sie eine Frage zum Produkt? |
Größe: 17,8 MB
DRM: Digitales Wasserzeichen
Dieses eBook enthält ein digitales Wasserzeichen und ist damit für Sie personalisiert. Bei einer missbräuchlichen Weitergabe des eBooks an Dritte ist eine Rückverfolgung an die Quelle möglich.
Dateiformat: PDF (Portable Document Format)
Mit einem festen Seitenlayout eignet sich die PDF besonders für Fachbücher mit Spalten, Tabellen und Abbildungen. Eine PDF kann auf fast allen Geräten angezeigt werden, ist aber für kleine Displays (Smartphone, eReader) nur eingeschränkt geeignet.
Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen dafür einen PDF-Viewer - z.B. den Adobe Reader oder Adobe Digital Editions.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen dafür einen PDF-Viewer - z.B. die kostenlose Adobe Digital Editions-App.
Zusätzliches Feature: Online Lesen
Dieses eBook können Sie zusätzlich zum Download auch online im Webbrowser lesen.
Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.
aus dem Bereich