🚀 Writing Custom Database Queries with @Query and JPQL in Spring Data JPA Most Spring Boot devs start with derived query methods — and they're great. But when your query logic gets complex, derived methods become unreadable nightmares like findByFirstNameAndLastNameAndAgeGreaterThanAndStatusIn(...). That's where @Query + JPQL saves the day. 💡 @Query("SELECT u FROM User u WHERE u.email = :email AND u.active = true") Optional<User> findActiveUserByEmail(@Param("email") String email); JPQL (Java Persistence Query Language) operates on entity classes and their fields, not database tables and columns. This means your queries are portable across databases and benefit from compile-time safety. Key wins with @Query: ✅ Complex multi-condition queries stay readable ✅ JOINs, aggregations, and GROUP BY without stored procedures ✅ Named parameters with @Param keep code clean ✅ Modifying queries with @Modifying + @Transactional for bulk updates/deletes @Modifying @Transactional @Query("UPDATE User u SET u.active = false WHERE u.lastLogin < :cutoffDate") int deactivateInactiveUsers(@Param("cutoffDate") LocalDate cutoffDate); #Java #SpringBoot #BackendDevelopment #SpringDataJPA #JPQL #DatabaseQueries
Jānis Ošs’ Post
More Relevant Posts
-
Working with Spring Data JPA and JPQL: One common mistake in JPA is treating LAZY and EAGER as query strategies. They are not. They are just default fetch behaviors — the real control comes from your queries. My rule of thumb: - Use LAZY by default - Use JOIN FETCH only when needed Example: @Query("SELECT b FROM Book b JOIN FETCH b.author") Why? - Avoids N+1 issues - Prevents overfetching - Gives explicit control over performance In practice, doesn't matter if you are using LAZY or EAGER, the rule is: - Need only Book -> query Book - Need Book + Author -> use JOIN FETCH * If LAZY is your default, it will load as EAGER for this query and use JOIN to select the data. For other queries and methods, it will keep the behavior as LAZY. * If EAGER is your default, it will load using your strategy (JOIN). That is, it would fill your relationship with or without your fetch, but you would not know which strategy it would use. By using JOIN FETCH, you are saying: Return all the data I need in a single query with a JOIN. Simple as that. #Java #SpringBoot #JPA #Hibernate #Backend #Microservices #SoftwareEngineering #Performance #CleanCode #SpringData
To view or add a comment, sign in
-
I used to think using Spring Data JPA meant I didn’t really need to worry about SQL anymore. It felt too easy. 😅 I remember building a feature that looked perfectly fine in code, clean repositories, simple method names, everything “just worked.” Until I started testing it with more data and suddenly the API got slower… and slower. 🐢 Not crashing. Not failing. Just… slower. I opened the logs and saw a flood of queries. One for users, then one for each user’s orders. 📄📄📄 That’s when it hit me, I had no idea what queries were actually running behind my code. That moment was a bit uncomfortable everything “worked”, but I clearly didn’t understand what was happening. 😬 A few things became very real after that: JPA hides complexity, but it doesn’t remove it 🎭 JPA makes things easy, but it doesn’t make database behavior go away ⚠️ Just because you didn’t write the query doesn’t mean it’s efficient. You still need to understand what’s being generated 🔍 Lazy vs eager loading isn’t just theory, it directly impacts performance ⚙️ That innocent looking repository method? It can cause an N+1 problem real quick 🚨 In real systems, this doesn’t show up during basic testing. It shows up as slow endpoints, high DB usage and confusing debugging sessions. 🧩 Now, I still use JPA the same way but I don’t trust it blindly. I check queries, think about fetching strategies and pay attention to what’s happening underneath. 👨💻 What I learned: If you’re using JPA without understanding the queries, you are debugging in the dark. Have you ever been surprised by what JPA was doing behind the scenes? 🤔 #Java #SoftwareEngineer #SpringMVC #SpringBoot #SpringDataJPA
To view or add a comment, sign in
-
I optimized a query that was taking 45 seconds down to 200ms. Here's exactly what I did: After 9 years with Java + Spring Boot + various databases, here are the database lessons that actually matter: 1. Indexes are not magic, they're a trade-off Every index speeds up reads but slows down writes Index what you query, not everything 2. N+1 queries will kill your app Use JOIN FETCH in JPQL or @EntityGraph Always check the SQL Hibernate is generating 3. Pagination is non-negotiable findAll() on a 10M row table is a career-limiting move Spring Data's Pageable is your best friend 4. Connection pools matter more than you think HikariCP defaults are a starting point, not gospel Monitor your pool metrics in production 5. Read replicas for read-heavy workloads Your reporting queries shouldn't compete with your transactional queries 6. EXPLAIN ANALYZE before any optimization Never guess. Always measure. Most performance problems I've seen weren't code problems. They were database design problems. What's your worst database horror story? #Java #SpringBoot #Database #Performance #SQL #BackendDevelopment
To view or add a comment, sign in
-
Day 23. I stopped writing raw SQL in my repositories. Not because SQL is bad. Because Spring Data JPA was already doing it for me. And I didn’t know. I used to write this: @Query("SELECT * FROM users WHERE email = :email", nativeQuery = true) User findByEmail(@Param("email") String email); It worked. Until I realized I was solving a problem the framework had already solved. Here’s what actually happens: → Queries tied directly to database structure → Harder to refactor when schema changes → Less readable for other developers → You bypass what Spring Data JPA already gives you That’s not flexibility. That’s unnecessary complexity. So I changed it. (see implementation below 👇) User findByEmail(String email); No SQL. Same result. Better readability. Now: → Let JPA generate simple queries → Use @Query only when needed → Native SQL only for edge cases The hard truth: → Writing SQL feels powerful → But overusing it makes your code rigid → Most queries don’t need it Using SQL is easy. Knowing when NOT to use it is what makes you a backend developer. Are you still writing SQL for simple queries? 👇 Drop it below #SpringBoot #Java #JPA #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
-
🔥 Day 41 of My Spring Boot Journey Today I explored some powerful features of Spring Data JPA that can significantly optimize database operations 📌 What I learned: ✅ Static Projection → Fetch only required fields using interface-based projections ✅ Dynamic Projection → Create flexible queries where the result type can be decided at runtime ✅ Custom Queries (JPQL & Native SQL) → Write optimized queries using @Query → Use @Param for named parameters → Perform UPDATE & INSERT using @Modifying and @Transactional 💡 Key takeaway: Instead of fetching entire entities, projections help improve performance and make APIs more efficient. Also understood the difference between: 🔹 SQL → works on tables 🔹 JPQL → works on entity classes 📁 Implemented all concepts with hands-on projects including: ✔ Static Projection ✔ Dynamic Projection ✔ Custom Queries Big thanks to my mentor for simplifying these advanced concepts 🙌 #SpringBoot #Java #BackendDevelopment #JPA #Hibernate #LearningInPublic #100DaysOfCode Hyder Abbas
To view or add a comment, sign in
-
-
A #Flink event-stream processing project doesn't have to be accessible SQL *or* powerful Java. User defined functions (UDFs) let you work in SQL, and write Java to extend what SQL can do when you need. In this post, I've given six examples of when it helps to extend Flink SQL with short, targeted Java functions. https://lnkd.in/eT9A59p5
To view or add a comment, sign in
-
🚀 Stop Confusing JPQL with SQL — This Might Be Holding You Back! Most beginners in Spring Boot make this mistake 👇 They treat JPQL and SQL as the same thing… but they’re NOT. Let’s simplify it 🔥 🔹 JPQL = Works on Java Objects (Entities) 🔹 SQL = Works on Database Tables 👉 That’s it. That’s the core difference. But here’s where it gets interesting 👇 ⚡ JPQL ✔ Cleaner & object-oriented ✔ Database independent ✔ Perfect for JPA/Hibernate projects ⚡ SQL (MySQL) ✔ More control over queries ✔ Better for complex joins ✔ Needed for performance tuning --- 💡 Real Developer Insight: If you're only using JPQL, you're missing control. If you're only using SQL, you're missing abstraction. 👉 Smart developers know WHEN to use WHAT. --- 🎯 Interview Gold Line: “JPQL works on entities, SQL works on tables.” --- If this cleared your confusion, drop a 👍 and follow for more real backend concepts! #Java #SpringBoot #JPA #Hibernate #BackendDevelopment #SQL #CodingTips #Developers #Learning
To view or add a comment, sign in
-
-
I read two JetBrains articles recently that seem to completely contradict each other. One says: ❌ don't use data classes for entities in Kotlin. The other says: ✅ data classes are a great fit for entities. Same company. Opposite advice. The difference? One is about JPA. The other is about Spring Data JDBC. Here's why it matters. ── Spring Data JPA (Hibernate) manages entities as tracked, mutable objects. To do that, it needs to: → create proxy subclasses for lazy loading (class must be non-final) → call a no-arg constructor when loading from DB → inject fields via reflection after construction (fields must be mutable) Kotlin's data class breaks all three of these. Final. Immutable. No no-arg constructor. ── Spring Data JDBC is a completely different philosophy. No dirty checking. No proxies. No lazy loading. You call save() → SQL runs. You call findById() → result maps to your object. That's it. And because it uses constructor-based mapping, data classes are a natural fit. Immutable val fields? Great. final class? No problem. copy() to update instead of mutation? That's exactly the pattern. ── So "don't use data classes for entities" really means "...when using JPA." It's not a rule about Kotlin + databases in general. The two frameworks look similar from the outside — both are Spring Data, both talk to relational DBs. But they have fundamentally different models for how objects and databases interact. Once you see that, the contradiction disappears. 📝 Wrote a full breakdown on Medium — link in the comments. #Kotlin #SpringBoot #SpringData #JPA #Backend
To view or add a comment, sign in
-
-
When I first started with Spring Data JPA, this honestly felt like magic User findByEmail(String email); No SQL . No implementation. No query. And somehow… it worked. I used it for a long time before asking How is this actually possible? When I started with Spring Boot, I assumed this was just framework magic and I think many of us have felt the same. But that skips the most interesting part. It is not magic. It is a parser. Spring treats this method name: findByEmail() as a mini query language. Yes — the method name itself. Internally, Spring Data uses a parser called PartTree to read it. It breaks it into meaning like - * find → create a select query * By → start parsing criteria * Email → match an entity property If your entity has - private String email; Spring can derive a query from the method name.That is called query derivation using naming conventions.And this is where it gets deeper.Spring does not directly generate SQL.It first derives JPQL.Then Hibernate converts JPQL into database-specific SQL. This getSomeUserStuff() does not work. Because the parser does not understand it. But this findByEmailAndStatus() works because it follows a grammar.That is not just convention. That is a contract. And one detail many of use miss - Spring validates these derived queries at startup. Not later. So if you write: findByEmailAddress() but your entity does not have - emailAddress , your application can fail fast during startup. That is intentional framework design. Sometimes the most elegant engineering is hiding inside the APIs we use every day. #SpringBoot #Java #JPA #Hibernate #BackendDevelopment
To view or add a comment, sign in
-
Database evolution and migrations at scale 🐘☕🚀 When building scalable APIs with Spring Boot and relational databases, two fundamental concepts always come into play: 🏗️ DDL (Data Definition Language): creating tables, altering columns, adding indexes. 📝 DML (Data Manipulation Language): inserting, updating, deleting records. How these two pillars are managed often defines the maturity of an application's lifecycle. Let's look at two common strategies depending on the project phase: Scenario 1: Early-stage agility (DDL Only | Without Flyway) When modeling a project's domain from scratch, it is common to rely on hibernate.ddl-auto=update. The framework takes control, automatically generating and altering tables based on the @Entity classes. This provides incredible speed to test hypotheses. However, because this approach is restricted to DDL, it doesn't help insert default records or migrate legacy data in a traceable way. Scenario 2: Predictability at scale (DDL + DML | With Flyway + Validate) As the project grows and predictability becomes non-negotiable, introducing Flyway and switching Spring to ddl-auto=validate is the standard path. This grants full control over both DDL and DML in the exact same pipeline. The role of Hibernate shifts to an auditor: it validates if the real database perfectly reflects the Java entities. If there is a mismatch, the application fails to start (Fail-Fast), ensuring total data integrity. 💡 Example: Migrating a 1:N to an N:N Relationship Imagine refactoring a system where a User previously had only one Role (1:N), but business rules changed, and now a user can have multiple roles (N:N). The production database is already full of data. ❌ If relying on ddl-auto=update: The framework will successfully create the new join table (DDL). However, it will be completely empty. The existing relationship data is orphaned, and users lose their roles. ✅ If relying on Flyway: A single SQL migration script solves the puzzle. (Check the image below for the exact code!) 👇 Both tools are incredible in the right context. Knowing when to transition from the agility of the Update tool to the absolute control of Flyway is what enables teams to scale securely without data loss. At what stage of a project do you usually introduce database versioning? #Java #SpringBoot #SoftwareArchitecture #Flyway #Hibernate #Database #TechTips
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development