🚀 DevOps Day 24 | Multi Container Deployment | Java + MySQL | Part 2 After learning Docker Compose basics, I moved into real production architecture. Today I deployed: • Java Backend Application • MySQL Database • Multi Container Setup This is where DevOps becomes real-world engineering. My application.properties: spring.datasource.url=jdbc:mysql://mysqldb:3306/bank spring.datasource.username=bankuser spring.datasource.password=bankpass123 Notice something interesting? Instead of localhost, I used: mysqldb Why? Because Docker Compose automatically creates internal networking between containers. Now My Docker Compose File: version: '3.8' services: mysqldb: image: mysql:8 container_name: mysql environment: MYSQL_ROOT_PASSWORD: admin@123 MYSQL_DATABASE: bank MYSQL_USER: bankuser MYSQL_PASSWORD: bankpass123 volumes: - ./mysql_data:/var/lib/mysql backend: image: bank container_name: bankapp build: context: ./backend environment: SPRING_DATASOURCE_URL: jdbc:mysql://mysqldb:3306/products SPRING_DATASOURCE_USERNAME: bankuser SPRING_DATASOURCE_PASSWORD: bankpass123 ports: - "8080:8080" depends_on: - mysqldb Key Learnings: mysqldb Database container backend Java application container depends_on Ensures MySQL starts before Java environment Inject runtime variables ports Expose service externally This setup allowed my Java application to communicate with MySQL automatically. This is exactly how Microservices Architecture works. And honestly… this felt like real DevOps work. Part 3 Coming Next Volumes + Production Level Data Persistence GitHub Repo https://lnkd.in/gjw9Fuxe #DevOps #DockerCompose #Java #MySQL #Microservices #CloudEngineering
Nischal koirala’s Post
More Relevant Posts
-
🚨 Debugging a Tricky Timezone Issue with Spring Boot + Dockerized PostgreSQL Recently, I ran into a confusing issue while connecting a Spring Boot application to a PostgreSQL database running inside Docker. Everything looked correct: ✔ Database was up and running ✔ Credentials were valid ✔ Connection URL was correct But still, the application kept failing with this error: FATAL: invalid value for parameter "TimeZone": "Asia/Calcutta" 🔍 What made it tricky? When I checked inside PostgreSQL: SHOW timezone; It returned: 👉 Asia/Kolkata ✅ So the database configuration was perfectly fine. 💡 Root Cause The issue was not in PostgreSQL at all. 👉 The JVM (Java environment) was still using the old timezone: Asia/Calcutta ❌ PostgreSQL no longer accepts this deprecated value, which caused the connection to fail during startup. ✅ Solutions Here are the ways to fix it: 1️⃣ Set JVM timezone explicitly (Recommended) -Duser.timezone=Asia/Kolkata 2️⃣ Set timezone programmatically in Spring Boot static { TimeZone.setDefault(TimeZone.getTimeZone("Asia/Kolkata")); } 3️⃣ Ensure Hibernate uses correct timezone spring.jpa.properties.hibernate.jdbc.time_zone=Asia/Kolkata 🎯 Key Learning Sometimes the issue is not where the error points. 👉 Even if PostgreSQL is correctly configured, 👉 JVM-level timezone mismatches can break the connection. 💬 Takeaway Always verify timezone at all levels: ✔ Database ✔ Application ✔ JVM / Environment #SpringBoot #PostgreSQL #Docker #Java #BackendDevelopment #Debugging #SoftwareEngineering
To view or add a comment, sign in
-
-
𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗤𝘂𝗲𝗿𝘆 𝗠𝗶𝗰𝗿𝗼𝘀𝗲𝗿𝘃𝗶𝗰𝗲 Mastering database queries with Spring Boot + JPA In real-world applications, the efficiency of your system often depends on how well you write database queries. While basic CRUD operations are simple, production systems require much more like efficient filtering, optimized joins, aggregations, and handling complex query scenarios. I built this microservice to demonstrate how modern backend systems handle basic to advanced querying patterns using Spring Boot and JPA. Source code: https://lnkd.in/g9b78BnS This project focuses on writing clean, efficient, and scalable queries which something every backend developer should master. 𝗛𝗶𝗴𝗵𝗹𝗶𝗴𝗵𝘁𝘀 • Real-world query scenarios exposed via REST APIs • Performance-focused design (N+1 problem and optimization) • Combination of JPA, JPQL, and native SQL • Practical handling of relational data • Clean and maintainable architecture 𝗪𝗵𝗮𝘁’𝘀 𝗖𝗼𝘃𝗲𝗿𝗲𝗱 • Derived queries (method name-based) • Pagination and sorting for large datasets • Search using LIKE queries • Join queries and fetch join optimization • N+1 problem and its solution • Aggregations (count, sum, group by) • Native SQL queries • Dynamic queries using Specification API • Projections (interface and DTO-based) • Subqueries (average, max, nested queries) • Exists / Not Exists queries • Window functions (ranking, top-N queries, running totals) • Indexed queries for performance • Relationship handling (one-to-many, many-to-many) • Soft delete implementation • Stored procedure integration 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 Poorly written queries quickly become a bottleneck: • Slow APIs • High database load • Increased latency • Scalability limitations This project demonstrates how to avoid these issues using proper query design and optimization techniques. 𝗧𝗲𝗰𝗵 𝗦𝘁𝗮𝗰𝗸 • Java 21 • Spring Boot (REST APIs) • Spring Data JPA (Hibernate) • PostgreSQL • Lombok • Maven This project is useful for developers who want to: • Improve their JPA and SQL skills • Understand real-world query patterns • Learn performance optimization techniques "Efficient queries are the foundation of high-performance systems." #Java #SpringBoot #JPA #Hibernate #SQL #Database #BackendDevelopment #Microservices #Performance #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
Spring Boot DAY 26 – JPQL vs Native Query When working with Spring Data JPA, you often need custom queries. That’s where JPQL and Native Queries come into play 👇 🔹 JPQL (Java Persistence Query Language) JPQL is an object-oriented query language defined by Java Persistence API (JPA). It works with: ✔ Entity class names ✔ Java field names ✔ Object relationships 👉 It does NOT use table names or column names directly. ✅ Example: @Query("SELECT e FROM Employee e WHERE e.salary > :salary") List<Employee> findHighSalaryEmployees(@Param("salary") double salary); Here: Employee= Entity class salary= Java field 💡 JPQL works on the entity model, not the database schema. 🎯 Advantages: ✔ Database independent ✔ Cleaner & object-oriented ✔ Easy to maintain ✔ Portable across databases 🔹 Native Query Native Query uses pure SQL. It works with: ✔ Table names ✔ Column names ✔ Database-specific functions ✅ Example: @Query(value = "SELECT * FROM employee WHERE salary > :salary", nativeQuery = true) List<Employee> findHighSalaryEmployees(@Param("salary") double salary); Here: employee = Table name salary = Column name 💡 You are directly interacting with the database. 🎯 Advantages: ✔ Full database control ✔ Use complex joins ✔ Use DB-specific features (e.g., LIMIT, stored procedures) ✔ Better for performance tuning in complex cases 🆚 JPQL vs Native Query – Key Differences FeatureJPQLNative QueryQuery TypeObject-basedSQL-basedUsesEntity namesTable namesDB DependencyIndependentDB-specificPortabilityHighLowAdvanced SQLLimitedFull support🧠 When Should You Use What? ✅ Use JPQL when: You want database independence Your query is simple to moderate You prefer object-oriented coding ✅ Use Native Query when: You need complex joins You want database-specific optimization You are using stored procedures or advanced SQL 🎯 Simple Rule 👉 JPQL = Work with Objects 👉 Native Query = Work with Database Both are powerful. The smart developer chooses based on project requirements 💡 If you're learning Spring Boot, understanding this difference is crucial for writing optimized and maintainable applications 🚀
To view or add a comment, sign in
-
-
HIBERNATE'S HIDDEN TRAP: EAGER VS LAZY LOADING (PART 1) 🛌⚡ In Hibernate, there are two ways to load data, and both of them can kill your performance if you aren't careful. 1. THE EAGER TRAP 🍔 Eager loading is "greedy." It fetches the parent and all related children in one go. Sounds efficient? Until you realize that fetching one User just triggered a massive chain reaction that loaded 500 Orders, 2000 Items, and 5000 Reviews into memory. Your "simple" query just became a memory bomb. 2. THE LAZY TRAP 💤 Lazy loading is "procrastinating." it only fetches the children when you actually ask for them. But if you ask for them inside a loop, you trigger the N+1 problem. One query to fetch the list, and then 100 more queries to fetch the details. 3. THE "DETACHED ENTITY" CRASH 💥 We’ve all seen the LazyInitializationException. This happens when you try to access lazy data after the DB transaction has closed. It’s Hibernate’s way of saying, "You should have asked for this earlier!" In Part 2, I’ll show you how to use Join Fetching to get the best of both worlds. #Hibernate #Java #ORM #DatabasePerformance #BackendDevelopment #SoftwareEngineering #JavaPersistenceAPI #DatabaseDesign #PerformanceTuning #TechTips #CodingLife #SoftwareArchitecture #API #SQL
To view or add a comment, sign in
-
-
🚀 How Spring Data JPA Works Internally Today I took some time to deeply understand how Spring Data JPA actually works behind the scenes. Most of the time, we simply write: studentRepository.findAll(); But internally, a lot happens: We create a Repository Interface Spring creates a Proxy Object for it The proxy intercepts the method call Hibernate converts it into an SQL query The SQL runs on the database The result is returned as Java objects Simple flow: Your Code → Repository → Proxy Class → Hibernate → SQL Query → Database This is what makes Spring Data JPA so powerful and developer-friendly. ✔ Less boilerplate code ✔ Automatic CRUD operations ✔ Query generation from method names ✔ Seamless Hibernate integration ✔ Faster backend development Example: List<Student> students = studentRepository.findAll(); Behind the scenes, Spring and Hibernate handle everything automatically. It may look like magic when you start learning backend development, but once you understand the internal flow, it becomes much easier to work with. #Java #SpringBoot #SpringDataJPA #Hibernate #BackendDevelopment #Programming #SoftwareEngineering #JavaDeveloper #Coding #WebDevelopment
To view or add a comment, sign in
-
-
Written by Luke Thompson - MongoDB Champion published on Friends of OpenJDK (Foojay.io), learn how to build a Java faceted full-text search API! In the tutorial, he'll walk through using a interesting dataset which showcases how you can effectively pair machine learning/AI-generated data with more traditional search to produce fast, cheap, repeatable, and intuitive search engines. Dive in here 👉 https://lnkd.in/gm6a2Y77 #mongodb #java #nosql #database #atlas
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
-
-
🚀 Spring Boot Learning Series – Day 4 Today was more about understanding data handling and persistence in backend development. 🔹 What I learned today: • Revised MongoDB key concepts • Understood ORM (Object Relational Mapping) • Learned about Hibernate and EclipseLink • Introduction to JPA (Java Persistence API) • Spring Data JPA • Spring Data MongoDB • Query Method DSL • Criteria API 💡 My Understanding: ORM helps us interact with databases using Java objects instead of writing raw SQL queries. Tools like Hibernate and EclipseLink implement JPA, which acts as a standard for database operations. Spring Data JPA and Spring Data MongoDB make it even easier by reducing boilerplate code. We can directly write methods like findByName() without manually writing queries, which is part of Query Method DSL. I also explored how more complex queries can be handled using the Criteria API. Today helped me understand how backend applications manage and interact with databases efficiently. Next, I will try to integrate MongoDB or SQL database into my Spring Boot project. #SpringBoot #Java #BackendDevelopment #MongoDB #JPA #Hibernate #LearningJourney #SoftwareDevelopment #100DaysOfCode
To view or add a comment, sign in
-
After getting comfortable with Spring Data JPA and understanding what Hibernate was doing behind the scenes, I thought I had things figured out. 🤔 Then I tried Spring JDBC. Honestly, it felt like going backwards at first. 😅 No repositories. No auto-generated queries. Just plain SQL staring back at me. 📄 I remember writing a simple query and thinking, “Wait… that’s it?” 😶 No hidden joins. No extra queries. No surprises. 🚫 That’s when it started to make sense: With JDBC, what you write is exactly what runs ⚙️ No abstraction means no guessing but also no shortcuts ⚠️ You’re responsible for mapping, queries and performance 🧠 It’s simple… but not easy at scale 📈 At the same time, I started thinking about when to use each: If I need to build features quickly → I reach for JPA 💫 If I’m debugging performance issues → I look at Hibernate 🔄 If I need full control over queries → I go with JDBC 🎯 It made me realize something important: Different tools solve different problems, not everything needs abstraction. #SpringBoot #SpringDataJPA #Hibernate #SpringJDBC #Java #BackendDevelopment #SoftwareEngineering #Database #TechLearning #DeveloperJourney
To view or add a comment, sign in
-
Yesterday we talked about how Lombok can crash your app through Hibernate relationships. Today, let’s talk about the other silent killer in those exact same entities: The N+1 Query Problem. If you work with Spring Data JPA long enough, you will eventually write a piece of code that looks completely fine, passes all unit tests, and then completely chokes your database in production. Usually, the culprit is the N+1 problem. The Trap: Let’s say you have a User entity with a @OneToMany relationship to Order. You want to fetch 100 users and print their order totals. You write a simple repository call: userRepository.findAll() (This is 1 query).Then, you loop through those 100 users and call user.getOrders(). What you think happens: Hibernate fetches the users and their orders efficiently. What actually happens: Because relationships are (and should be!) FetchType.LAZY by default, Hibernate executes 1 query to get the 100 users, and then 100 additional queries—one for each user—to fetch their orders. You just hit your database 101 times for a single API request. Multiply that by 1,000 concurrent users, and your DBA is calling you in a panic. 😅 The Senior Fixes: 1. The Quick Fix: JOIN FETCH Instead of using standard findAll(), write a custom JPQL query: SELECT u FROM User u JOIN FETCH u.orders This forces Hibernate to grab everything in a single, efficient JOIN query. 2. The Elegant Fix: @EntityGraph If you don't want to write custom queries, Spring Boot lets you use Entity Graphs to dynamically define which lazy associations should be fetched eagerly for a specific method call. 3. The Ultimate Fix: DTO Projections Stop fetching full Managed Entities if you just need to read data! Write a query that maps directly to a Record or DTO. It bypasses the Hibernate proxy lifecycle entirely and is blazing fast. JPA makes the easy things trivial, but it makes the hard things incredibly dangerous if you don't look at the generated SQL. What is your team's standard way of catching N+1 queries before they hit production? Do you use a specific tool, or rely on code reviews? 👇 #Java #SpringBoot #Hibernate #BackendDevelopment #Microservices #SoftwareEngineering #PerformanceTuning #CleanCode
To view or add a comment, sign in
More from this author
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