Slide 1

Slide 1 text

Mastering Java Persistence Best Practices for Cloud-Native Applications and Modernization

Slide 2

Slide 2 text

Endures knowledge Throughout humanity Temples, Caves as database Why do we need databases anyway?

Slide 3

Slide 3 text

Database evolutions

Slide 4

Slide 4 text

Why Do Modern Applications Need Data Storage? The new opportunities The current opportunity It's where the state is

Slide 5

Slide 5 text

Maturity Model Database flavors Paradigms Persistence landscape State of affairs https://survey.stackoverflow.co/2023/

Slide 6

Slide 6 text

Development lifecycle very often starts with immature data structures Changing a database type in existing applications is complex and expensive. Over time, maintenance of data and schema evolution gets challenging First thing we do Persistence landscape Change Maintenance State of affairs Evolutionary Data

Slide 7

Slide 7 text

The rules of Software Architecture Everything in Software Architecture is a trade-off Why is more important than How

Slide 8

Slide 8 text

Business Isolation Performance The success at Software Architecture

Slide 9

Slide 9 text

SQL Database Database solutions Polyglot Persistence key value key key key value value value Wide-Column Graph Document Key Value NoSQL Database

Slide 10

Slide 10 text

Apollo Key-value Structure Ares Love Beauty War Sun Aphrodite Key Value

Slide 11

Slide 11 text

Use Case Description Caching Speeds up data retrieval by storing frequently accessed data in memory, reducing the need to fetch it from the backend. Session Management Stores and manages user sessions, enhancing application performance and scalability. Real-time Analytics Powers real-time dashboards and analytics by swiftly processing and aggregating data. Pub/Sub Messaging Facilitates real-time communication between components through publish-subscribe messaging patterns. Redis Use cases

Slide 12

Slide 12 text

Simplify Schema Identify Key Patterns Use Contextual Keys Batching Operations Cache-friendly Design Avoid Complex Joins Beware of Over-Normalization Avoid Bloated Values Limit Indexes Redis Do and Don'ts

Slide 13

Slide 13 text

Redis Clusters

Slide 14

Slide 14 text

Apollo Aphrodite Ares Kratos Duty Dead Gods Love, happy Sun War 13 Color Sword Row-key Columns Wide-Column Structure Duty Duty weapon

Slide 15

Slide 15 text

Apache Cassandra User Cases Use Case Description Online Retail Managing e-commerce platforms, handling product catalogs, user profiles, and transaction records. Social Media Analytics Monitoring and analyzing social media interactions, tracking trends, and user engagement. Real-Time Analytics Enabling quick analysis of data streams for instant insights, critical in financial and logistics sectors. Logging and Monitoring Centralized storage and analysis of logs and monitoring data from applications and servers.

Slide 16

Slide 16 text

Apache Cassandra Modeling tips Denormalize When Necessary Design for Query Patterns Choose Optimal Column Families Utilize Secondary Indexes Compression and Bloom Filters Avoid Over-Denormalization Limit Column Count Avoid Overusing Secondary Indexes

Slide 17

Slide 17 text

1 2 3 4 5 6 7 8 9 11 12 10 Client R1 R2 R3 1 2 3 4 5 6 7 8 9 11 12 10 R4 R5 R6 DC1 DC2 Apache Cassandra Cluster

Slide 18

Slide 18 text

{ "name":"Diana", "duty":[ "Hunt", "Moon", "Nature" ], "siblings":{ "Apollo":"brother" } } Document Structure

Slide 19

Slide 19 text

MongoDB User Cases Use Case Description Content Management Store and manage diverse content types like articles, images, and videos with schema flexibility. Catalog Management Efficiently organize and categorize products or items with changing attributes and metadata. Mobile Applications Provide offline capabilities and sync data seamlessly once online, enhancing user experience. Social Media Platforms Facilitate rapid storage and retrieval of user-generated content, profiles, and social interactions.

Slide 20

Slide 20 text

MongoDB Modeling tips Leverage Embedded Documents Design Around Use Cases Employ Indexes Judiciously Normalize When Logical Stay Flexible with Arrays Avoid Over-Embedding Steer Clear of Monolithic Documents Don’t Over-Index Beware of the One-Size-Fits-All Approach

Slide 21

Slide 21 text

MongoDB Cluster

Slide 22

Slide 22 text

MongoDB Cluster

Slide 23

Slide 23 text

Apollo Ares Kratos was killed by was killed by killed killed Graph Structure

Slide 24

Slide 24 text

Neo4J Modeling tips Avoid Over-Reliance on Joins Steer Clear of Over-Connecting Nodes Don’t Overcomplicate Graph Design Beware of Property Index Overuse Embrace Relationship-Driven Design Craft Efficient Traversal Paths Use Labels and Types Wisely Leverage Indexing for Nodes Utilize Property Indexes

Slide 25

Slide 25 text

Neo4J User Cases Use Case Description Social Networks Modeling user profiles, friendships, and interactions for effective social networking platforms. Recommendation Engines Powering personalized recommendations by analyzing connections and preferences. Knowledge Graphs Organizing and querying complex relationships in fields like healthcare, finance, and research. Fraud Detection Uncovering hidden patterns and connections indicative of fraudulent activities. Network Analysis Analyzing intricate relationships in data networks, such as transportation and communication.

Slide 26

Slide 26 text

Neo4J Leader Follower Follower Read Replica Read Replica

Slide 27

Slide 27 text

Scalability Flexibility key-value Column Document Graph Time-series Scalability vs Flexibility Query and speed

Slide 28

Slide 28 text

Application vs. Database

Slide 29

Slide 29 text

Application (Object Oriented Language) Mismatch Database (Relational) Object Challenges in a database land Different paradigms: Apps x DBMS Tables

Slide 30

Slide 30 text

Mapping Mismatch 1 * Addresses Inheritance Polymorphism Encapsulation Types Normalization Denormalization Structure Application Database key value key key key value value value wide-Column Graph Document Key Value Challenges in a database land Different paradigms: Apps x DBMS

Slide 31

Slide 31 text

Driver Data Mapper DAO Database integration Data Access Patterns Handling Data Integration in Java Active Record Repository DTO

Slide 32

Slide 32 text

Driver Database integration Data Mapping Database Application Data Mapper Active Record Repository DAO Data-oriented Programing Object Oriented Programming

Slide 33

Slide 33 text

Database-oriented Programming 4 Principles Database Data-oriented Programing 1. Separating code (behavior) from data. 2. Representing data with generic data structures. 3. Treating data as immutable. 4. Separating data schema from data representation.

Slide 34

Slide 34 text

Object Oriented Programming Principles Application Object Oriented Programming 1. Expose behavior and Hide data 2. Abstraction 3. Polymorphism

Slide 35

Slide 35 text

Driver Data Mapping try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS){ Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(QUERY);) { // Extract data from result set while (rs.next()) { // Retrieve by column name System.out.print("ID: " + rs.getInt("id")); System.out.print(",name: " + rs.getInt("name")); System.out.print(",birthday: " + rs.getString("birthday")); System.out.println(",city: " + rs.getString("city")); System.out.println(",street: " + rs.getString("street")); …} } Complex relation w/ business logic Code flexibility

Slide 36

Slide 36 text

Data Mapper Data Mapping @Entity public class Person { @Id @GeneratedValue(strategy = AUTO) Long id; String name; LocalDate birthday; @ManyToOne List
address; … } impedance mismatch centralize mapper responsibility public class PersonRowMapper implements RowMapper { @Override public Person mapRow(ResultSet rs, int rowNum) throws SQLException { Person person = new Person(); person.setId(rs.getInt("ID")); return person; } }

Slide 37

Slide 37 text

Data Access Object Data Mapping public interface PersonDAO { List getAll(); void update(Person person); void delete(Person person); void insert(Person person); } Centralize Data operations impedance mismatch

Slide 38

Slide 38 text

Active Record Data Mapping @Entity public class Person extends PanacheEntity { public String name; public LocalDate birthday; public List
addresses; } Person person =...; // persist it person.persist(); List people = Person.listAll(); // finding a specific person by ID person = Person.findById(personId); SOLID breaking Higher domain's responsibility

Slide 39

Slide 39 text

Repository Data Mapping Far from database Domain oriented @Entity public class Person { private @Id Long id; private @Column String name; private @Column LocalDate birthday; private @ManyToOne List
addresses; } public interface PersonRepository extends {} Person person =...; // persist it repository.save(person); List people = repository.findAll(); // finding a specific person by ID person = repository.findById(personId);

Slide 40

Slide 40 text

Database integration Data Mapping Client Database Database Client Mapper DAO Repository Data mapping and conversion

Slide 41

Slide 41 text

Flexibility vs Complexity, Use with Caution Database Layers

Slide 42

Slide 42 text

DTO Entity Resource DTO Flexibility vs Complexity, Use with Caution Database

Slide 43

Slide 43 text

Database metrics Biz. transactions Oversized / downsized Invalid/stale connections Apps on await state Fixed cache size No cache usage Consistency impacts w/ distributed cache Complex mapping Auto-generated schemas On-prem x Cloud Many NoSQL types SQL x NoSQL x NewSQL Eager x Lazy loading N+1 Problem Hard to change db types Persistence Config. Data storage Data Manipulation Cache Conn. Pool Framework What's next?

Slide 44

Slide 44 text

books.a4j.dev/mastering-persistence Expand your Knowledge Deliver high-performance Java solutions Get your copy today! @otaviojava @kvarel4