Filter
Exclude
Time range
-
Near
The 7 JPA Relationship Patterns Every Spring Boot Developer Should Know Learn when to use OneToOne, OneToMany, ManyToMany, composite keys, and join entities through a production-ready Spring Boot project. 🔗 medium.com/@ivangfr/the-7-jp… #SpringBoot #JPA #Java #BackendDev #Hibernate
33
📚 Learning Notes: Why Refresh Tokens Should Be Persisted While learning JWT authentication, I came across an interesting question: 🤔 If JWTs are stateless, why would we store refresh tokens in a database? The answer comes down to one thing: 🔐 Control. 🔹 The Problem Access tokens are usually short-lived. ⏱️ 15 minutes ⏱️ 30 minutes ⏱️ 1 hour If an access token is stolen, the damage is limited. Refresh tokens are different. They often live for months or even a year. If a refresh token is compromised, an attacker could continuously generate new access tokens. That's a much bigger risk. 🔹 Why Persist Refresh Tokens? Instead of treating refresh tokens as completely stateless, many systems store metadata about them. Benefits: ✅ Token Revocation Logout becomes meaningful. Delete the refresh token record and the token can no longer be used. ✅ Device Management Track how many active sessions a user has. Example: • Laptop • Mobile • Tablet Each device can have its own refresh token record. ✅ Suspicious Activity Detection Unexpected token usage can be identified and revoked. ✅ Token Rotation Each refresh token can be used exactly once. When exchanged: Old Token ❌ New Token ✅ This dramatically reduces the value of stolen refresh tokens. 🔹 TDD Approach Following the Red → Green → Refactor cycle: 🔴 Red Write a failing test: • Register a user • Check if a refresh token record exists in the database The test fails because no persistence mechanism exists yet. 🟢 Green Create a RefreshToken entity: RefreshToken ├─ id ├─ expiresAt ├─ userId ├─ createdAt └─ updatedAt Save a refresh token record whenever a user authenticates. Run tests again → Pass ✅ 🔹 User ↔ Refresh Token Relationship A common design: User (1) │ │ ▼ Refresh Tokens (Many) This allows a single user to maintain multiple active sessions across devices. TypeORM makes this easy using: • OneToMany • ManyToOne relationships. 🔹 JWT ID (JTI) One concept I found particularly interesting was using the JWT ID claim. Instead of storing large amounts of data inside the refresh token: JWT ├─ sub ├─ role └─ jti The jti references the database record. Benefits: ✅ Smaller tokens ✅ Easy revocation ✅ Better auditing ✅ Simpler token rotation 🔹 Additional Security Opportunities Once refresh tokens are persisted, we unlock features such as: 🛡️ Logout Everywhere 🛡️ Session Tracking 🛡️ Refresh Token Rotation 🛡️ Revocation Lists 🛡️ Expired Token Cleanup Jobs These become difficult or impossible with fully stateless refresh tokens. 💡 Biggest takeaway JWT authentication is often described as stateless. But in practice, many production systems intentionally add state back to refresh tokens. Why? Because security isn't just about issuing tokens. It's about being able to control them after they've been issued. #JWT #Authentication #RefreshToken #NodeJS #TypeScript #BackendDevelopment #SoftwareEngineering #WebSecurity #LearningInPublic #PostgreSQL #TypeORM
📚 Day 3 of Building a Microservices-Based Project Over the past few days, I've been working on the Authentication Service and learning more about how authentication and session management are handled in backend systems. Today's focus was on stateless vs stateful authentication, JWTs, Access Tokens, Refresh Tokens, and token persistence. Some of the things I explored: 🔹 Understanding the difference between stateless and stateful authentication 🔹 Learning how JWT-based authentication enables stateless authorization 🔹 Understanding the difference between Access Tokens and Refresh Tokens 🔹 Generating JWTs and storing them securely in cookies 🔹 Creating a dedicated Refresh Token entity in PostgreSQL using TypeORM 🔹 Persisting refresh tokens in the database instead of relying solely on stateless JWTs 🔹 Learning how JWT IDs can be be used to link tokens with database records 🔹 Updating integration tests to verify refresh token persistence during user registration One thing I found particularly interesting was the distinction between stateless and stateful authentication. With stateless authentication, all the information needed to validate a user is contained within the token itself, allowing services to verify requests without querying a database. This can improve scalability and simplify distributed systems. With stateful authentication, session information is stored on the server side, making it easier to manage active sessions, revoke access, and enforce security policies. By storing refresh tokens in the database, we introduce a stateful component that enables features such as session management, token revocation, and token rotation. Another valuable lesson was seeing how quickly controllers can become overloaded with responsibilities and how moving logic into dedicated services makes the codebase easier to maintain and test. Still learning a lot about authentication, security, and microservice architecture, but each step is helping me better understand how production-ready systems are designed. @codersGyan #Microservices #BackendDevelopment #NodeJS #TypeScript #JWT #Authentication #PostgreSQL #TypeORM #SoftwareEngineering #LearningInPublic #WebDevelopment
31
Completed the Third Module by Coding Shuttle @sudoanuj which is based on the Relationship mapping between the tables, how JDBC and Spring Data JPA helps to map the POJO with the database. Learned Cascading and many other important concepts like pagination and projection. The homework assignment was heavily focused on the relationship mappings. The first homework assignment was related to subject, student, department, admission record and professor which is basically a college management system where the ERD diagram was provided by @sudoanuj which made things easier. The tables have different relationships with each other. Some tables have OneToOne relationship and some have ManyToMany. Let's Understand the annotations with examples: 1. OneToOne: A Student can have only one Admission record. So that's why a OneToOne relationship is established between these two tables. 2. OneToMany: A Professor can teach more than one subject. So there's a OneToMany relationship established between these two tables and vice versa for ManyToOne. 3. ManyToMany: Many students can be taught by many professors. mappedBy is used to define the non-owning (inverse) side of a bidirectional entity relationship. It is present on the inverse side of the relationship, telling JPA that the other side owns the foreign key. JsonIgnore is a Jackson library annotation used to prevent specific entity fields or relationships from being serialized into JSON. It is commonly used to hide sensitive data like passwords or to break infinite recursion loops caused by bidirectional database relationships. Heavily used in ManyToMany relationships. JoinTable with JoinColumn defines the owning side of a ManyToMany relationship in JPA. It explicitly defines the intermediate join table and the foreign key columns used to establish the relationship between two database tables. The second homework project was an Author and Book management system where we had to map authors and the books they published. There are only two tables in this project with a ManyToMany relationship between authors and books — because one author can write many books and one book can have many authors. The main challenge was implementing all these APIs: Create a new book and author Retrieve a list of all books and authors Retrieve a single book or author by ID Update book and author details Delete a book or author Find books by title Find books published after a certain date Find authors by name Find all books by a specific author Some APIs required custom query methods in the Repository layer using Spring Data JPA's method naming conventions. Definitely a solid project! Learned a lot in this module. Will dive more in-depth into topics like Cascading and N 1 query optimization. #Java #SpringBoot #SpringDataJPA #BackendDevelopment #LearningInPublic #JavaDeveloper #CodingJourney
1
2
114
2/4 One example: OneToMany is gone. In ObjectQuel, relationships are already defined by the FK-owning side (ManyToOne / OneToOne). The inverse side wasn't defining a relationship. It was only describing where related entities should be hydrated. It will become InverseOf.
1
12
Replying to @sriram_gsr16
Actually many problem here: Returning Entity Directly Exposes internal DB structure to API consumers. If User has password, roles, audit fields, etc., they may leak accidentally. Lazy Loading Issues JPA relationships (@OneToMany, @ManyToOne) can trigger: LazyInitializationException unexpected DB queries Infinite JSON Recursion Bidirectional mappings can break serialization: Tight Coupling API becomes tightly coupled with database entity structure. Any DB change can break frontend contracts. No Proper Error Handling orElseThrow() throws generic exception. User gets ugly 500 instead of clean 404 response. No ResponseEntity No control over headers, status codes, or API response format.
36
Day 4 of learning Spring Boot 🚀 Today’s progress: 1.Hibernate Entity Lifecycle, EntityManager & Persistence Context 2.OneToOne, OneToMany, ManyToOne & ManyToMany mappings 3.Cascading Types #SpringBoot #Java #BackendDevelopment #JavaDeveloper #100DaysOfCode
1
1
84
Day 14 - Spring Boot Learned how database relationships work using OneToMany and ManyToOne mappings. Implemented a real-world example: User to Orders relationship using JPA & Hibernate. #SpringBoot #Java #BackendDevelopment
1
4
74
May 13
Agencies charge $8,000/mo to repurpose your podcast. You still have to brief them, review it, and chase deadlines. OneToMany does it for $2,500. The difference is AI, not quality. onetomany-0p7p.polsia.app

20
May 12
You recorded a 45-minute interview last month. You've posted once since then. The transcript is sitting in a folder. OneToMany turns that one recording into 20 pieces of content before your competitor posts again. onetomany-0p7p.polsia.app

6
May 11
Your competitor with half your insight posts twice a day. You have 11 unrecorded podcast ideas and zero content. OneToMany turns one recording into 20 pieces. onetomany-0p7p.polsia.app

7
May 10
You recorded a podcast. It got 47 listens. The ideas in it were worth $100k in deals. Nobody saw them. OneToMany turns one recording into 20 pieces of content. onetomany-0p7p.polsia.app

1
9
May 10
OneToMany. One video from a founder. 20 pieces of content out the other side. Blog posts, clips, newsletters, threads. The math: $2,500/mo, AI does 80% of the work. onetomany.polsia.app
3
Replying to @Deylama58
با یه تیبل هم میشه منطقیش هم وقتی ریلیشن دیتابیسشون one to one هست نیازی نیست که بری یه انتیتی جدا تعریف کنی و کلا یه انتیتی باید وجود داشته باشه. تو وقتی میری برای کامنت انتیتی جدا بزنی که مثلا ریلیشنش OneToMany باشه مثلا هر یوزر چند کامنت بتونه بزاره.
1
48
En JPA, TOUTES les relations doivent être LAZY. ​Rappel des valeurs par défaut : ✅ @OneToMany / @ManyToMany : Lazy (bon comportement) ❌ @ManyToOne / @OneToOne : Eager (le piège classique) ​Pourquoi forcer le LAZY partout ? Une relation EAGER est chargée à chaque requête, même lorsque vous n'en avez pas besoin. Résultat : requêtes SQL superflues, surconsommation de mémoire et apparition du fameux problème N 1. La règle : @ManyToOne(fetch = FetchType.LAZY) @OneToOne(fetch = FetchType.LAZY) Chargez ensuite explicitement les données nécessaires via @EntityGraph ou JOIN FETCH. ​Principe d'architecture à retenir : Le chargement d'une relation doit être une décision explicite du code appelant, et non un comportement caché ou subi depuis l'entité.
56
Le problème N 1 en JPA/Hibernate : Vous chargez N entités, puis vous accédez à une relation lazy (@OneToMany, @ManyToOne). Hibernate déclenche 1 requête pour la liste, puis 1 requête par entité pour charger la relation. 100 commandes avec leurs lignes → 101 requêtes SQL au lieu d'1 seule. 3 façons de l'éviter, de la plus utilisée à la moins utilisée : → @EntityGraph sur la méthode du repository : Déclaratif, lisible, directement sur le Spring Data Repository. Solution par défaut aujourd'hui. @EntityGraph(attributePaths = "items") → JOIN FETCH en JPQL : Requête explicite qui charge la relation en un seul SELECT avec JOIN. Utile dans les requêtes custom. SELECT o FROM Order o JOIN FETCH o.items → Projection JPA : Si vous n'avez pas besoin des entités complètes, sélectionnez directement les champs utiles via un DTO ou une interface de projection. Plus performant, moins de mémoire, mais demande plus de code. Comment le détecter : → spring.jpa.show-sql=true en développement pour voir les requêtes générées → Hibernate Statistics pour compter les requêtes par transaction Règle simple : Si le nombre de requêtes dépend de la taille du résultat, c'est un problème N 1. #Java #SpringBoot #Hibernate #Performance
45
That might be ok for a ManyToOne, but could be trouble for OneToMany. If each relation has 1000's of entities, that's A LOT of hydrations! I typically explicitly choose when to use this.
15
Daily Log 🪵 ​Spring Boot: Deep-dived into OneToMany and ManyToOne mappings; polished my understanding of Validation constraints. ​DSA: Tackled the "Lowest Common Ancestor" (Medium) in Binary Trees and knocked out 3 Linked List revisions. ​#SpringBoot #Java #DataStructures
7
55
SCGT – Deccan Chapter One To Many Business Presentation 7 एप्रिल | सायं. 5:30 कोल्हापूर इंजिनिअरिंग असोसिएशन हॉल राजेंद्र मिठारी | शैलेंद्र मोहिते | आशितोष गडकरी Network. Connect. Grow. Don’t miss it. #SCGT #KolhapurBusiness #BusinessNetworking #OneToMany
18
Day 6/45 | Post 1/3 | Job Challenge 🎯 today's plan. putting it here so I actually do it. Hibernate — what it is project setup — saving, fetching, updating data — relationships: OneToOne, OneToMany, ManyToMany — Eager vs Lazy fetch — HQL basics Spring — IoC and Dependency Injection — Spring vs Spring Boot — Autowiring SQL — SELECT with WHERE and JOIN — GROUP BY HAVING — subqueries — indexes — aggregate functions let's see how much of this actually gets done by tonight.
1
2
94