Spring Boot 3 and Spring Framework 6 (Christian Ullenboom) (Z-Library)
Author: Christian Ullenboom
技术
Say goodbye to dependencies, bogged-down code, and inflexibility! With the Spring framework and Spring Boot, you’ll painlessly create Java applications that are production ready. Start with the basics: containers for Spring-managed beans, Spring framework modules, and proxies. Then learn to connect to relational databases, implement Jakarta Persistence, use Spring Data JPA, and work with NoSQL databases. Get the right know-how for modern software development with Spring and Java!
📄 File Format:
PDF
💾 File Size:
31.5 MB
68
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
(This page has no text content)
📄 Page
2
The Rheinwerk Computing series from Rheinwerk Publishing offers new and established professionals comprehensive guidance to enrich their skillsets and enhance their career prospects. Our publications are written by leading experts in the fields of programming, administration, security, analytics, and more. Each book is detailed and hands-on to help readers develop essential, practical skills that they can apply to their daily work. For further information, please visit our website: www.rheinwerk-computing.com. Christian Ullenboom Java: The Comprehensive Guide 2023, 1126 pages, paperback and e-book www.rheinwerk-computing.com/5557 Bernd Öggl, Michael Kofler Docker: Practical Guide for Developers and DevOps Teams 2023, 491 pages, paperback and e-book www.rheinwerk-computing.com/5650 Sebastian Springer React: The Comprehensive Guide 2024, approx. 676 pp., paperback and e-book www.rheinwerk-computing.com/5705 Philip Ackermann JavaScript: The Comprehensive Guide 2022, 982 pages, paperback and e-book www.rheinwerk-computing.com/5554 Johannes Ernesti, Peter Kaiser Python 3: The Comprehensive Guide 2022, 1036 pages, paperback and e-book www.rheinwerk-computing.com/5566 Rheinwerk Computing
📄 Page
3
Christian Ullenboom Spring Boot 3 and Spring Framework 6
📄 Page
4
(This page has no text content)
📄 Page
5
Imprint This e-book is a publication many contributed to, specifically: Editor Meagan White Acquisitions Editor Hareem Shafi German Edition Editor Almut Poll, Patricia Schiewald Translation Winema Language Services, Inc. Copyeditor Julie McNamee Cover Design Graham Geary Photo Credit Shutterstock: 110415056/© liewluck; 65652385/© concept w Layout Design Vera Brauner Production E-Book Hannah Lane Typesetting E-Book III-satz, Germany We hope that you liked this e-book. Please share your feedback with us and read the Service Pages to find out how to contact us. The Library of Congress Cataloging-in-Publication Control Number for the printed edition is as follows: 2023945877 ISBN 978-1-4932-2475-3 (print) ISBN 978-1-4932-2476-0 (e-book) ISBN 978-1-4932-2477-7 (print and e-book) © 2024 by Rheinwerk Publishing, Inc., Boston (MA) 1st edition 2024 1st German edition published 2023 by Rheinwerk Verlag, Bonn, Germany
📄 Page
6
Contents Preface ....................................................................................................................................................... 25 1 Introduction 33 1.1 History of Spring Framework and Your First Spring Project ............................... 33 1.1.1 Tasks of Java Platform, Standard Edition ....................................................... 33 1.1.2 Enterprise Requirements ..................................................................................... 33 1.1.3 Development of Java Enterprise Frameworks .............................................. 34 1.1.4 Rod Johnson Develops a Framework ............................................................... 34 1.1.5 Spring Framework: Many Configurations Are Required ........................... 36 1.2 Spring Boot ............................................................................................................................... 37 1.2.1 Spring Boot Versions ............................................................................................. 38 1.2.2 Support Period ......................................................................................................... 39 1.2.3 Alternatives to Spring ........................................................................................... 40 1.2.4 Setting Up a Spring Boot Project ....................................................................... 43 1.2.5 Building Spring Projects in Development Environments .......................... 48 1.3 Spring Boot Project: Dependencies and Starter ...................................................... 53 1.3.1 Project Object Model with Parent Project Object Model .......................... 54 1.3.2 Dependencies as Imports .................................................................................... 57 1.3.3 Milestones and the Snapshots Repository ..................................................... 58 1.3.4 Configuring Annotation Processors ................................................................. 58 1.3.5 Starter: Dependencies of the Spring Initializr .............................................. 59 1.4 Getting Started with Configurations and Logging ................................................. 61 1.4.1 Turning Off the Banner ........................................................................................ 62 1.4.2 Logging API and Simple Logging Facade for Java ........................................ 62 1.5 Summary ................................................................................................................................... 65 2 Containers for Spring-Managed Beans 67 2.1 Spring Container .................................................................................................................... 67 2.1.1 Start Container ........................................................................................................ 67 2.1.2 Instantiate SpringApplication ............................................................................ 68 2.1.3 SpringApplicationBuilder * .................................................................................. 69 2.1.4 What main(…) Does and Doesn’t Do ................................................................ 70 2.1.5 The run(…) Method Returns ConfigurableApplicationContext ............... 707
📄 Page
7
Contents2.1.6 Context Methods .................................................................................................... 71 2.2 Package Structure of the Date4u Application .......................................................... 74 2.3 Pick Up Spring-Managed Beans through Classpath Scanning .......................... 76 2.3.1 Fill Container with Beans ..................................................................................... 76 2.3.2 @Component .......................................................................................................... 77 2.3.3 @Repository, @Service, @Controller .............................................................. 80 2.3.4 Control Classpath Scanning More Precisely with @ComponentScan * .............................................................................................. 82 2.4 Interactive Applications with the Spring Shell ......................................................... 89 2.4.1 Include a Spring Shell Dependency .................................................................. 89 2.4.2 First Interactive Application ................................................................................ 91 2.4.3 Write Shell Component: @ShellComponent, @ShellMethod ................ 91 2.5 Injecting Dependencies ...................................................................................................... 95 2.5.1 Build Object Graphs ............................................................................................... 95 2.5.2 Inversion of Control and Dependency Injection .......................................... 97 2.5.3 Injection Types ........................................................................................................ 97 2.5.4 PhotoService and PhotoCommands ................................................................ 102 2.5.5 Multiple Dependencies ........................................................................................ 105 2.5.6 Behavior in Case of a Missing Component .................................................... 106 2.5.7 Optional Dependency ........................................................................................... 107 2.5.8 Cyclic Dependencies * ........................................................................................... 109 2.5.9 Inject Other Things ................................................................................................ 110 2.6 Configuration Classes and Factory Methods ............................................................ 111 2.6.1 What @Component Can’t Do ............................................................................ 111 2.6.2 @Configuration and @Bean .............................................................................. 111 2.6.3 Parameter Injection of an @Bean Method .................................................... 119 2.6.4 @Configuration Bean and Lite Bean ............................................................... 119 2.6.5 InjectionPoint * ........................................................................................................ 121 2.6.6 Static @Bean Methods * ...................................................................................... 124 2.6.7 @Import and @ImportSelector * ...................................................................... 125 2.7 Abstraction and Qualifications ....................................................................................... 127 2.7.1 Bean Name and Alias ............................................................................................ 127 2.7.2 AwtBicubicThumbnail for Thumbnails ........................................................... 128 2.7.3 Basic Types ................................................................................................................ 131 2.7.4 ObjectProvider ......................................................................................................... 140 2.7.5 @Order and @AutoConfigurationOrder * ..................................................... 142 2.7.6 Behavior in Selected Inheritance Relationships * ........................................ 144 2.8 Beans Lifecycle ........................................................................................................................ 146 2.8.1 @DependsOn .......................................................................................................... 146 2.8.2 Delayed Initialization (Lazy Initialization) ...................................................... 1478
📄 Page
8
Contents2.8.3 Bean Initialization Traditional ........................................................................... 149 2.8.4 InitializingBean and DisposableBean * ........................................................... 155 2.8.5 Inheritance of the Lifecycle Methods .............................................................. 155 2.8.6 *Aware Interfaces * ................................................................................................ 156 2.8.7 BeanPostProcessor * .............................................................................................. 159 2.8.8 Register Spring-Managed Beans Somewhere Else ...................................... 163 2.8.9 Hierarchical Contexts * ......................................................................................... 165 2.8.10 Singleton and Prototype Stateless or Stateful ............................................. 168 2.9 Annotations from JSR 330, Dependency Injection for Java * ............................. 169 2.9.1 Dependency for the JSR 330 Standard Annotation .................................... 169 2.9.2 Map JSR 330 Annotations to Spring ................................................................. 170 2.10 Auto-Configuration .............................................................................................................. 170 2.10.1 @Conditional and Condition ............................................................................. 171 2.10.2 If, Then: @ConditionalOn* .................................................................................. 173 2.10.3 Turn on Spring Debug Logging .......................................................................... 180 2.10.4 Controlling Auto-Configurations Individually * ........................................... 182 2.11 Spring Expression Language ............................................................................................. 185 2.11.1 ExpressionParser ..................................................................................................... 185 2.11.2 SpEL in the Spring (Boot) API .............................................................................. 186 2.12 Summary ................................................................................................................................... 190 3 Selected Modules of the Spring Framework 191 3.1 Helper Classes in Spring Framework ............................................................................. 191 3.1.1 Components of org.springframework ............................................................. 191 3.2 External Configuration and the Environment .......................................................... 193 3.2.1 Code and External Configuration ..................................................................... 193 3.2.2 Environment ............................................................................................................ 194 3.2.3 Inject Values with @Value .................................................................................. 195 3.2.4 Get Environment Assignments via @Value and ${…} ................................ 197 3.2.5 @Value and Default Values ................................................................................ 198 3.2.6 Access to Configurations ..................................................................................... 200 3.2.7 Nested/Hierarchical Properties ......................................................................... 205 3.2.8 Map Special Data Types ....................................................................................... 211 3.2.9 Relaxed Bindings .................................................................................................... 216 3.2.10 Property Sources ..................................................................................................... 218 3.2.11 Define Spring Profiles ........................................................................................... 231 3.2.12 Activate Profiles ...................................................................................................... 235 3.2.13 Spring-Managed Beans Depending on Profile ............................................. 2369
📄 Page
9
Contents3.3 At the Beginning and End .................................................................................................. 238 3.3.1 CommandLineRunner and ApplicationRunner ............................................ 238 3.3.2 At the End of the Application ............................................................................. 241 3.3.3 Exit Java Programs with Exit Code * ................................................................. 242 3.4 Event Handling ....................................................................................................................... 247 3.4.1 Participating Objects ............................................................................................. 247 3.4.2 Context Events ........................................................................................................ 248 3.4.3 ApplicationListener ................................................................................................ 249 3.4.4 @EventListener ....................................................................................................... 250 3.4.5 Methods of the Event Classes ............................................................................ 251 3.4.6 Write Event Classes and React to the Events ................................................ 251 3.4.7 An Event Bus of Type ApplicationEventPublisher ........................................ 252 3.4.8 Generic Events Using the PayloadApplicationEvent Example ................ 253 3.4.9 Event Transformations ......................................................................................... 256 3.4.10 Sequences by @Order ........................................................................................... 256 3.4.11 Filter Events by Conditions .................................................................................. 256 3.4.12 Synchronous and Asynchronous Events ......................................................... 257 3.4.13 ApplicationEventMulticaster * ........................................................................... 258 3.4.14 Send Events via ApplicationContext ................................................................ 259 3.4.15 Attach Listener to SpringApplication * ............................................................ 259 3.4.16 Listener in spring.factories * ............................................................................... 260 3.5 Resource Abstraction with Resource ............................................................................ 261 3.5.1 InputStreamSource and Resource .................................................................... 261 3.5.2 Load Resources ........................................................................................................ 263 3.5.3 Inject Resources via @Value ............................................................................... 264 3.6 Type Conversion with ConversionService .................................................................. 265 3.6.1 ConversionService .................................................................................................. 266 3.6.2 DefaultConversionService and ApplicationConversionService ............... 267 3.6.3 ConversionService as Spring-Managed Bean ................................................ 269 3.6.4 Register Your Own Converters with the ConverterRegistry ..................... 270 3.6.5 Printer and Parser ................................................................................................... 275 3.6.6 FormatterRegistry .................................................................................................. 277 3.6.7 DataBinder ................................................................................................................ 279 3.7 Internationalization * .......................................................................................................... 283 3.7.1 Possibilities for Internationalization with Java SE ...................................... 283 3.7.2 MessageSource under Subtypes ....................................................................... 284 3.8 Test-Driven Development with Spring Boot ............................................................. 289 3.8.1 Test Related Entries from Spring Initializr ..................................................... 289 3.8.2 Annotation @Test .................................................................................................. 290 3.8.3 Test Case for the FileSystem Class .................................................................... 290 3.8.4 Test Multitier Applications, Exchange Objects ............................................ 29410
📄 Page
10
Contents3.8.5 Mocking Framework Mockito ............................................................................ 298 3.8.6 @InjectMocks .......................................................................................................... 301 3.8.7 Verify Behavior ........................................................................................................ 302 3.8.8 Testing with ReflectionTestUtils ....................................................................... 303 3.8.9 With or Without Spring Support ....................................................................... 305 3.8.10 Test Properties ......................................................................................................... 308 3.8.11 @TestPropertySource ........................................................................................... 309 3.8.12 @ActiveProfiles ....................................................................................................... 310 3.8.13 Appoint Deputy ....................................................................................................... 311 3.8.14 @DirtiesContext ..................................................................................................... 313 3.9 Testing Slices Using a JSON Example * ......................................................................... 314 3.9.1 JSON ............................................................................................................................ 314 3.9.2 Jackson ....................................................................................................................... 315 3.9.3 Write a Java Object in JSON ................................................................................ 315 3.9.4 Testing JSON Mappings: @JsonTest ................................................................ 318 3.9.5 Mapping with @JsonComponent ..................................................................... 321 3.10 Scheduling * ............................................................................................................................. 324 3.10.1 Scheduling Annotations and @EnableScheduling ..................................... 325 3.10.2 @Scheduled ............................................................................................................. 325 3.10.3 Disadvantages of @Scheduled and Alternatives ........................................ 328 3.11 Types from org.springframework.*.[lang|util] ......................................................... 328 3.11.1 org.springframework.lang.*Null* Annotations ............................................ 329 3.11.2 Package org.springframework.util ................................................................... 330 3.11.3 Package org.springframework.data.util ......................................................... 331 3.12 Summary ................................................................................................................................... 335 4 Selected Proxies 337 4.1 Proxy Pattern ........................................................................................................................... 337 4.1.1 Proxy Deployment in Spring ............................................................................... 339 4.1.2 Dynamically Generate Proxies ........................................................................... 340 4.2 Caching ....................................................................................................................................... 343 4.2.1 Optimization through Caching .......................................................................... 343 4.2.2 Caching in Spring .................................................................................................... 344 4.2.3 Component with the @Cacheable Method .................................................. 345 4.2.4 Use @Cacheable Proxy ......................................................................................... 346 4.2.5 @Cacheable + Condition ..................................................................................... 348 4.2.6 @Cacheable + Unless ........................................................................................... 349 4.2.7 @CachePut ............................................................................................................... 35011
📄 Page
11
Contents4.2.8 @CacheEvict ............................................................................................................ 351 4.2.9 Specify Your Own Key Generators .................................................................... 352 4.2.10 @CacheConfig ......................................................................................................... 358 4.2.11 Cache Implementations ....................................................................................... 358 4.2.12 Caching with Caffeine .......................................................................................... 359 4.2.13 Disable the Caching in the Test ......................................................................... 360 4.3 Asynchronous Calls ............................................................................................................... 361 4.3.1 @EnableAsync and @Async Methods ............................................................ 362 4.3.2 Example with @Async .......................................................................................... 362 4.3.3 The CompletableFuture Return Type ............................................................... 365 4.4 TaskExecutor * ........................................................................................................................ 369 4.4.1 TaskExecutor Implementations ........................................................................ 370 4.4.2 Set Executor and Handle Exceptions ............................................................... 372 4.5 Spring and Bean Validation .............................................................................................. 374 4.5.1 Parameter Checks ................................................................................................... 374 4.5.2 Jakarta Bean Validation (JSR 303) ..................................................................... 375 4.5.3 Dependency on Spring Boot Starter Validation ........................................... 375 4.5.4 Photo with Jakarta Bean Validation Annotations ....................................... 376 4.5.5 Inject and Test a Validator .................................................................................. 378 4.5.6 Spring and the Bean Validation Annotations ............................................... 380 4.5.7 Bean Validation Annotations to Methods ..................................................... 382 4.5.8 Validation Everywhere Using a Configuration Example ........................... 382 4.5.9 Test Validation * ...................................................................................................... 383 4.6 Spring Retry * ........................................................................................................................... 387 4.6.1 Spring Retry Project ............................................................................................... 387 4.6.2 @Retryable ............................................................................................................... 389 4.6.3 Fallback with @Recover ....................................................................................... 392 4.6.4 RetryTemplate ......................................................................................................... 394 4.7 Summary ................................................................................................................................... 395 5 Connecting to Relational Databases 397 5.1 Set Up an H2 Database ....................................................................................................... 397 5.1.1 Brief Introduction to the H2 Database ............................................................ 397 5.1.2 Install and Launch H2 ........................................................................................... 398 5.1.3 Connect to the Database via the H2 Console ............................................... 402 5.1.4 Date4u Database Schema ................................................................................... 404 5.2 Realize Database Accesses with Spring ....................................................................... 407 5.2.1 Spring Helper ........................................................................................................... 40712
📄 Page
12
Contents5.3 Spring Boot Starter JDBC .................................................................................................... 408 5.3.1 Include the JDBC Starter in the Project Object Model ................................ 408 5.3.2 Provide JDBC Connection Data .......................................................................... 410 5.3.3 Inject DataSource or JdbcTemplate .................................................................. 410 5.3.4 Connection Pooling ................................................................................................ 413 5.3.5 Log JDBC Accesses .................................................................................................. 414 5.3.6 JDBC org.springframework.jdbc Package and Its Subpackages .............. 415 5.3.7 DataAccessException ............................................................................................ 415 5.3.8 Auto-Configuration for DataSource * .............................................................. 418 5.3.9 Addressing Multiple Databases ......................................................................... 419 5.3.10 DataSourceUtils * ................................................................................................... 421 5.4 JdbcTemplate .......................................................................................................................... 422 5.4.1 Execute Any SQL: execute(…) .............................................................................. 422 5.4.2 SQL Updates: update(…) ....................................................................................... 423 5.4.3 Query Individual Values: queryForObject(…) ................................................. 423 5.4.4 Define a Placeholder for a PreparedStatement ............................................ 424 5.4.5 Query Whole Row: queryForMap(…) ................................................................ 425 5.4.6 Query Multiple Rows with One Element: queryForList(…) ........................ 426 5.4.7 Read Multiple Rows and Columns: queryForList(…) ................................... 426 5.5 Data Types for Mapping to Results ............................................................................... 427 5.5.1 RowMapper .............................................................................................................. 428 5.5.2 RowCallbackHandler ............................................................................................. 433 5.5.3 ResultSetExtractor ................................................................................................. 434 5.6 NamedParameterJdbcTemplate ..................................................................................... 437 5.6.1 Type Relationships of *JdbcTemplate .............................................................. 438 5.6.2 Methods of the NamedParameterJdbcTemplate ........................................ 439 5.6.3 Pass Values of NamedParameterJdbcTemplate through a Map ............ 439 5.6.4 SqlParameterSource .............................................................................................. 439 5.6.5 Access to Underlying Objects * .......................................................................... 442 5.7 Batch Operations * ................................................................................................................ 443 5.7.1 Batch Methods for JdbcTemplate ..................................................................... 443 5.7.2 BatchPreparedStatementSetter ........................................................................ 444 5.7.3 Batch Methods at NamedParameterJdbcTemplate ................................... 449 5.7.4 SqlParameterSourceUtils ..................................................................................... 450 5.7.5 Configuration Properties ..................................................................................... 450 5.8 BLOBs and CLOBs * ................................................................................................................ 451 5.8.1 SqlLobValue .............................................................................................................. 452 5.8.2 LobHandler and DefaultLobHandler ................................................................ 453 5.8.3 Read LOBs via AbstractLobStreamingResultSetExtractor ......................... 454 5.9 Subpackage org.springframework.jdbc.core.simple * .......................................... 455 5.9.1 SimpleJdbcInsert ..................................................................................................... 45613
📄 Page
13
Contents5.10 Package org.springframework.jdbc.object * ............................................................. 458 5.10.1 MappingSqlQuery .................................................................................................. 458 5.11 Transactions ............................................................................................................................. 460 5.11.1 ACID Principle .......................................................................................................... 460 5.11.2 Local or Global/Distributed Transactions ...................................................... 461 5.11.3 JDBC Transactions: Auto-Commit .................................................................... 461 5.11.4 PlatformTransactionManager ........................................................................... 462 5.11.5 TransactionTemplate ............................................................................................ 466 5.11.6 @Transactional ....................................................................................................... 470 5.12 Summary ................................................................................................................................... 472 6 Jakarta Persistence with Spring 473 6.1 World of Objects and Databases .................................................................................... 473 6.1.1 Transient and Persistent ...................................................................................... 474 6.1.2 Mapping Objects to Tables ................................................................................. 474 6.1.3 Java Libraries for O/R Mapping .......................................................................... 478 6.2 Jakarta Persistence ............................................................................................................... 479 6.2.1 Persistence Provider .............................................................................................. 480 6.2.2 Jakarta Persistence Provider and JDBC ............................................................ 481 6.2.3 Jakarta Persistence Coverage ............................................................................. 481 6.3 Spring Data JPA ...................................................................................................................... 482 6.3.1 Include Spring Boot Starter Data JPA ............................................................... 482 6.3.2 Configurations ......................................................................................................... 483 6.4 Jakarta Persistence Entity Bean ...................................................................................... 485 6.4.1 Develop an Entity Bean Class ............................................................................. 486 6.5 Jakarta Persistence API ....................................................................................................... 492 6.5.1 Getting the EntityManager from Spring ........................................................ 492 6.5.2 Search an Entity Bean by Its Key: find(…) ........................................................ 494 6.5.3 find(…) and getReference(…) ............................................................................... 496 6.5.4 Query Options with the EntityManager ......................................................... 497 6.6 Jakarta Persistence Query Language (JPQL) .............................................................. 498 6.6.1 JPQL Example with SELECT and FROM ............................................................ 498 6.6.2 Build and Submit JPQL Queries with createQuery(…) ................................ 500 6.6.3 Conditions in WHERE ............................................................................................ 502 6.6.4 Parameterize JPQL Calls ....................................................................................... 503 6.6.5 JPQL Operators and Functions ........................................................................... 506 6.6.6 Order Returns with ORDER BY ............................................................................ 51014
📄 Page
14
Contents6.6.7 Projection on Scalar Values ................................................................................. 511 6.6.8 Aggregate Functions ............................................................................................. 512 6.6.9 Projection on Multiple Values ............................................................................ 513 6.6.10 Named Declarative Queries (Named Queries) ............................................. 517 6.7 Call Database Functions and Send Native SQL Queries ....................................... 519 6.7.1 Call Database Functions: FUNCTION(…) ......................................................... 519 6.7.2 Use createNativeQuery(…) via EntityManager ............................................. 520 6.7.3 @NamedNativeQuery .......................................................................................... 521 6.7.4 @NamedNativeQuery with resultSetMapping ........................................... 522 6.8 Write Access with the EntityManager in Transactions ......................................... 525 6.8.1 Transactional Operations .................................................................................... 525 6.8.2 persist(…) ................................................................................................................... 525 6.8.3 EntityTransaction ................................................................................................... 526 6.8.4 PlatformTransactionManager with JpaTransactionManager ................. 527 6.8.5 @Transactional ....................................................................................................... 528 6.8.6 Save versus Update ................................................................................................ 529 6.8.7 remove(…) .................................................................................................................. 530 6.8.8 Synchronization or Flush ..................................................................................... 530 6.8.9 Query with UPDATE and DELETE ....................................................................... 531 6.9 Persistence Context and Other Transaction Controls ........................................... 531 6.9.1 Jakarta Persistence API and Database Operations ...................................... 531 6.9.2 States of an Entity Bean ....................................................................................... 532 6.10 Advanced ORM Metadata .................................................................................................. 535 6.10.1 Database-First and Code-First Approaches ................................................... 535 6.10.2 Set the Table Name via @Table ........................................................................ 536 6.10.3 Change the @Entity Name ................................................................................. 537 6.10.4 Persistent Attributes ............................................................................................. 537 6.10.5 @Basic and @Transient ....................................................................................... 539 6.10.6 Column Description and @Column ................................................................. 539 6.10.7 Entity Bean Data Types ......................................................................................... 542 6.10.8 Map Data Types with AttributeConverter ..................................................... 544 6.10.9 Key Identification ................................................................................................... 547 6.10.10 Embedded Types ..................................................................................................... 551 6.10.11 Entity Bean Inherits Properties from a Superclass ...................................... 553 6.11 Relationships between Entities ...................................................................................... 555 6.11.1 Supported Associations and Relationship Types ......................................... 555 6.11.2 1:1 Relationship ...................................................................................................... 555 6.11.3 Bidirectional Relationships ................................................................................. 559 6.11.4 1:n Relationship ...................................................................................................... 560 6.11.5 n:m Relationships * ................................................................................................ 56615
📄 Page
15
Contents6.12 FetchType: Lazy and Eager Loading ............................................................................... 567 6.12.1 Enumeration with FetchType ............................................................................. 568 6.12.2 Hibernate Type: PersistentBag .......................................................................... 568 6.12.3 1 + N Query Problem: Performance Anti-Pattern ........................................ 570 6.13 Cascading .................................................................................................................................. 573 6.13.1 CascadeType Enumeration Type ....................................................................... 574 6.13.2 Set CascadeType ..................................................................................................... 576 6.13.3 cascade=REMOVE versus orphanRemoval=true .......................................... 577 6.14 Repositories ............................................................................................................................. 577 6.14.1 Data Access Layer ................................................................................................... 578 6.14.2 Methods in the Repository .................................................................................. 580 6.14.3 SimpleJpaRepository ............................................................................................. 582 6.15 Summary ................................................................................................................................... 585 7 Spring Data JPA 587 7.1 What Tasks Does Spring Data Perform? ..................................................................... 587 7.1.1 For Which Systems Is Spring Data Available? ............................................... 588 7.2 Spring Data Commons: CrudRepository ..................................................................... 589 7.2.1 CrudRepository Type ............................................................................................. 589 7.2.2 Java Persistence API–Based Repositories ....................................................... 591 7.3 Subtypes of CrudRepository ............................................................................................. 594 7.3.1 ListCrudRepository ................................................................................................. 594 7.3.2 Technology-Specific [List]CrudRepository Subtypes .................................. 595 7.3.3 Selected Methods via Repository ...................................................................... 597 7.4 Paging and Sorting with [List]PagingAndSortingRepository ............................ 598 7.4.1 JpaRepository: Subttype of ListPagingAndSortingRepository and ListCrudRepository ................................................................................................. 599 7.4.2 Sort Type .................................................................................................................... 600 7.4.3 Sort.TypedSort<T> .................................................................................................. 601 7.4.4 Pageable and PageRequest ................................................................................. 602 7.4.5 Sort Paginated Pages ............................................................................................. 607 7.5 QueryByExampleExecutor * .............................................................................................. 608 7.5.1 Sample ....................................................................................................................... 608 7.5.2 QueryByExampleExecutor ................................................................................... 609 7.5.3 Sample into the Example ..................................................................................... 610 7.5.4 Build ExampleMatcher ......................................................................................... 611 7.5.5 Ignore Properties .................................................................................................... 61116
📄 Page
16
Contents7.5.6 Set String Comparison Techniques .................................................................. 612 7.5.7 Set Individual Rules with GenericPropertyMatcher .................................... 613 7.5.8 PropertyValueTransformer ................................................................................. 613 7.6 Formulate Your Own Queries with @Query ............................................................. 615 7.6.1 @Query Annotation .............................................................................................. 615 7.6.2 Modifying @Query Operations with @Modifying ..................................... 617 7.6.3 Fill IN Parameter by Array/Varg/Collection ................................................... 617 7.6.4 @Query with JPQL Projection ............................................................................ 618 7.6.5 Sort and Pageable Parameters ........................................................................... 619 7.6.6 Add New Query Methods .................................................................................... 620 7.6.7 Queries with Spring Expression Language Expressions ............................ 621 7.6.8 Using the @NamedQuery of an Entity Bean ................................................ 622 7.6.9 @Query Annotation with Native SQL ............................................................. 622 7.7 Stored Procedures * .............................................................................................................. 624 7.7.1 Define a Stored Procedure in H2 ....................................................................... 625 7.7.2 Calling a Stored Procedure via a Native Query ............................................. 627 7.7.3 Call a Stored Procedure with @Procedure ..................................................... 627 7.8 Derived Query Methods ..................................................................................................... 628 7.8.1 Individual CRUD Operations via Method Names ........................................ 628 7.8.2 Structure of the Derived Query Methods ....................................................... 629 7.8.3 Returns from Derived Query Methods ............................................................ 633 7.8.4 Asynchronous Query Methods .......................................................................... 633 7.8.5 Streaming Query Methods .................................................................................. 634 7.8.6 Advantages and Disadvantages of Derived Query Methods ................... 634 7.9 Criteria API and JpaSpecificationExecutor ................................................................. 635 7.9.1 Criteria API ................................................................................................................ 636 7.9.2 Functional Interface Specification .................................................................... 637 7.9.3 JpaSpecificationExecutor ..................................................................................... 638 7.9.4 Methods in JpaSpecificationExecutor ............................................................. 639 7.9.5 Specification Implementations ......................................................................... 639 7.9.6 Assemble Specification Instances ..................................................................... 641 7.9.7 Internals * .................................................................................................................. 642 7.9.8 Metamodel Classes ................................................................................................ 643 7.9.9 Cons of Using the Criteria API ............................................................................ 646 7.10 Alternatives to JDBC Jakarta Persistence .................................................................... 647 7.10.1 Querydsl ..................................................................................................................... 648 7.10.2 Spring Data JDBC .................................................................................................... 655 7.11 Good Design with Repositories ....................................................................................... 660 7.11.1 Abstractions through the Onion Architecture .............................................. 660 7.11.2 Think of the Interface Segregation Principle and the Onion! .................. 661 7.11.3 Fragment Interface ................................................................................................ 66217
📄 Page
17
Contents7.12 Projections ............................................................................................................................... 664 7.12.1 Perform Projections Yourself .............................................................................. 665 7.12.2 Projections in Spring Data ................................................................................... 665 7.12.3 Interface-Based Projection .................................................................................. 665 7.12.4 Projections with SpEL Expressions .................................................................... 667 7.12.5 Projections with Default Methods ................................................................... 668 7.12.6 Class-Based Projections ........................................................................................ 668 7.12.7 Dynamic Projections .............................................................................................. 669 7.13 [Fetchable]FluentQuery * ................................................................................................... 670 7.14 Auditing * .................................................................................................................................. 672 7.14.1 Auditing with Spring Data .................................................................................. 672 7.14.2 Auditing with Spring Data JPA ........................................................................... 672 7.14.3 AuditorAware for User Information ................................................................. 673 7.14.4 Outlook: Spring Data Envers ............................................................................... 674 7.15 Incremental Data Migration ............................................................................................. 675 7.15.1 Long Live the Data .................................................................................................. 676 7.15.2 Evolutionary Database Design ........................................................................... 676 7.15.3 Incremental Data Migration with Flyway ...................................................... 677 7.15.4 Flyway in Spring Boot: Migration Scripts ....................................................... 677 7.15.5 Migrations in Java Code ....................................................................................... 680 7.15.6 Flyway Migrations outside Spring .................................................................... 681 7.16 Test the Data Access Layer ................................................................................................ 682 7.16.1 What Do We Want to Test? ................................................................................ 682 7.16.2 Test Slices .................................................................................................................. 683 7.16.3 Deploy an In-Memory Test Database .............................................................. 684 7.16.4 Assign Connection to the Test Database ....................................................... 684 7.16.5 Build Tables with Initialization Scripts ............................................................ 686 7.16.6 Testcontainers Project .......................................................................................... 687 7.16.7 Demo Data ................................................................................................................ 689 7.16.8 @Sql and @SqlGroup ........................................................................................... 690 7.16.9 TestEntityManager ................................................................................................ 691 7.17 Summary ................................................................................................................................... 691 8 Spring Data for NoSQL Databases 693 8.1 Not Only SQL ............................................................................................................................ 693 8.2 MongoDB .................................................................................................................................. 694 8.2.1 MongoDB: Documents and Collections .......................................................... 694 8.2.2 About MongoDB ..................................................................................................... 69518
📄 Page
18
Contents8.2.3 Install and Start the MongoDB Community Server .................................... 696 8.2.4 GUI Tools for MongoDB ........................................................................................ 697 8.2.5 Spring Data MongoDB .......................................................................................... 698 8.2.6 MongoDB Application Programming Interfaces .......................................... 699 8.2.7 MongoDB Documents .......................................................................................... 700 8.2.8 MongoTemplate Class .......................................................................................... 701 8.2.9 MongoDB Repositories ......................................................................................... 704 8.2.10 Test MongoDB Programs ..................................................................................... 706 8.3 Elasticsearch ............................................................................................................................ 707 8.3.1 Text Search Is Different ........................................................................................ 707 8.3.2 Apache Lucene ......................................................................................................... 708 8.3.3 Documents and Fields .......................................................................................... 708 8.3.4 Index ........................................................................................................................... 708 8.3.5 Weaknesses of Apache Lucene .......................................................................... 709 8.3.6 Lucene Attachments: Elasticsearch and Apache Solr ................................. 710 8.3.7 Install and Launch Elasticsearch ....................................................................... 711 8.3.8 Spring Data Elasticsearch .................................................................................... 712 8.3.9 Documents ............................................................................................................... 713 8.3.10 ElasticsearchRepository ........................................................................................ 715 8.3.11 @DataElasticsearchTest ...................................................................................... 718 8.4 Summary ................................................................................................................................... 719 9 Spring Web 721 9.1 Web Server ............................................................................................................................... 721 9.1.1 Java Web Server ...................................................................................................... 722 9.1.2 Spring Boot Starter Web ...................................................................................... 723 9.1.3 Use Other Web Servers * ...................................................................................... 724 9.1.4 Adjust Port via server.port ................................................................................... 724 9.1.5 Serve Static Resources .......................................................................................... 725 9.1.6 WebJars ...................................................................................................................... 726 9.1.7 Transport Layer Security Encryption ................................................................ 726 9.2 Generate Dynamic Content .............................................................................................. 728 9.2.1 Stone Age: The Common Gateway Interface ................................................ 728 9.2.2 Servlet Standard ..................................................................................................... 729 9.2.3 Program @WebServlet ......................................................................................... 730 9.2.4 Weaknesses of Servlets ........................................................................................ 732 9.3 Spring Web MVC .................................................................................................................... 732 9.3.1 Spring Containers in Web Applications .......................................................... 733 9.3.2 @Controller .............................................................................................................. 73419
📄 Page
19
Contents9.3.3 @RestController ..................................................................................................... 735 9.3.4 Controller to [Service] to Repository ................................................................ 737 9.4 Hot Code Swapping .............................................................................................................. 738 9.4.1 Hot Swapping of the Java Virtual Machine ................................................... 739 9.4.2 Spring Developer Tools ......................................................................................... 739 9.5 HTTP ............................................................................................................................................. 740 9.5.1 HTTP Request and Response .............................................................................. 740 9.5.2 Set Up an HTTP Client for Testing Applications ........................................... 741 9.6 Request Matching ................................................................................................................. 742 9.6.1 @RequestMapping ................................................................................................ 742 9.6.2 @*Mapping .............................................................................................................. 743 9.6.3 More General Path Expressions and Path Matchers .................................. 743 9.6.4 @RequestMapping on Type ............................................................................... 744 9.7 Send Response ........................................................................................................................ 745 9.7.1 HttpMessageConverter in the Application .................................................... 745 9.7.2 Format Conversions of Handler Method Returns ....................................... 746 9.7.3 Mapping to JSON Documents ............................................................................ 746 9.7.4 ResponseEntity = Statuscode + Header + Body ............................................ 752 9.8 Evaluate Request ................................................................................................................... 755 9.8.1 Handler Methods with Parameters .................................................................. 755 9.8.2 Data Transmission from Client to Controller ................................................ 756 9.8.3 Data Acceptance via Parameters ...................................................................... 756 9.8.4 Evaluate Query Parameters ................................................................................ 757 9.8.5 Optional Query Parameters ................................................................................ 757 9.8.6 Map All Query Parameters .................................................................................. 758 9.8.7 Evaluate a Path Variable ...................................................................................... 760 9.8.8 MultipartFile ............................................................................................................ 763 9.8.9 Evaluate Header ...................................................................................................... 765 9.8.10 HttpEntity Subclasses RequestEntity and ResponseEntity * .................... 765 9.9 Type Conversion of the Parameters .............................................................................. 766 9.9.1 YearMonth Converter Example ......................................................................... 766 9.9.2 @DateTimeFormat and @NumberFormat ................................................... 767 9.9.3 Map Query Parameters and Form Data to a Bean ...................................... 768 9.9.4 Register Your Own Type Converters ................................................................ 772 9.9.5 URI Template Pattern with Regular Expressions ......................................... 774 9.10 Exception Handling and Error Message ...................................................................... 775 9.10.1 Map Exceptions to Status Codes Yourself ...................................................... 775 9.10.2 Escalates .................................................................................................................... 775 9.10.3 Configuration Properties server.error.* ........................................................... 777 9.10.4 Exception Resolver ................................................................................................. 78020
📄 Page
20
Contents9.10.5 Map Exception to Status Code with @ResponseStatus ............................ 780 9.10.6 ResponseStatusException ................................................................................... 781 9.10.7 Local Controller Exception Handling with @ExceptionHandler ............ 783 9.10.8 RFC 7807: “Problem Details for HTTP APIs” ................................................... 785 9.10.9 Global Controller Exception Handling with Controller Advice ............... 787 9.11 RESTful API ................................................................................................................................ 789 9.11.1 Principles behind REST .......................................................................................... 789 9.11.2 Implement REST Endpoints for Profiles .......................................................... 795 9.11.3 Data Transfer Objects ........................................................................................... 797 9.11.4 Best Practice: Don’t Deliver a Complete Collection at Once .................... 800 9.11.5 GET and DELETE on Individual Resources ....................................................... 800 9.11.6 POST and PUT with @RequestBody ................................................................. 802 9.11.7 UriComponents ....................................................................................................... 805 9.12 Asynchronous Web Requests * ........................................................................................ 806 9.12.1 Long Queries Block the Worker Thread ........................................................... 806 9.12.2 Write Asynchronously to the Output .............................................................. 807 9.12.3 A Handler Method Returns Callable ................................................................ 808 9.12.4 WebAsyncTask ........................................................................................................ 808 9.12.5 A Handler Method Returns DeferredResult ................................................... 809 9.12.6 StreamingResponseBody ..................................................................................... 809 9.13 Spring Data Web Support .................................................................................................. 811 9.13.1 Loading from the Repository .............................................................................. 811 9.13.2 Pageable and Sort as Parameter Types ........................................................... 812 9.13.3 Return Type Page .................................................................................................... 814 9.13.4 Querydsl Predicate as a Parameter Type ........................................................ 815 9.14 Documentation of a RESTful API with OpenAPI ...................................................... 817 9.14.1 Description of a RESTful API ................................................................................ 817 9.14.2 OpenAPI Specification ........................................................................................... 817 9.14.3 Where Does the OpenAPI Document Come From? .................................... 819 9.14.4 OpenAPI with Spring ............................................................................................. 819 9.14.5 springdoc-openapi ................................................................................................. 820 9.14.6 Better Documentation with OpenAPI Annotations .................................... 822 9.14.7 Generate Java Code from an OpenAPI Document ...................................... 822 9.14.8 Spring REST Docs .................................................................................................... 824 9.15 Testing the Web Layer ......................................................................................................... 825 9.15.1 Test QuoteRestController .................................................................................... 825 9.15.2 Annotation @WebMvcTest ................................................................................ 827 9.15.3 Writing a Test Method with MockMvc ........................................................... 827 9.15.4 Test REST Endpoints with the Server ............................................................... 830 9.15.5 WebTestClient ......................................................................................................... 83121
The above is a preview of the first 20 pages. Register to read the complete e-book.