Skip to main content

Why do I need to create Java Classes? Why don't just use database for searching?


The Bridge Between Data and Display

A Conceptual Guide to Java, Databases, and the "Why" behind the Code.

1. The Core Problem

When building a web application, you have data sitting in a Database (SQL Server) and a user waiting at a Browser. The challenge is moving that data efficiently and safely.

Beginners often ask: "Why do I need to create Java Classes (Student.java) and copy data into Lists? Why can't I just print the database results directly to the screen?"

To answer this, we must understand how the database actually talks to Java.


2. The Anatomy of a Connection

The ResultSet is NOT Data — It is a "Live Wire"

A common misconception is that when you run a query, the data is instantly sent to your Java program. It is not.

  • The ResultSet is a Cursor (Pointer). It points to a row on the database hard drive.

  • The Connection is a Pipe.

The Streaming Analogy:
Think of a ResultSet like a Phone Call.

  • When you say rs.next(), you are asking the database: "Read the next line to me."

  • The database reads it, sends it over the wire, and waits.

  • Crucial Rule: If you hang up the phone (conn.close()), the ResultSet dies immediately. You cannot read from it anymore.


3. The "Direct Print" Approach (And Why We Don't Use It)

Technically, you could keep the connection open, pass the ResultSet to your JSP, and print data while the connection is live.

The Visualization:
[Browser] <---> [JSP/Servlet] <======(HELD OPEN)======> [Database]

The Problem: Resource Starvation

  • Databases have a strict limit on active connections (e.g., 100 concurrent users).

  • If you hold the connection open while the JSP renders (which is slow), you are "hogging the phone line."

  • If 100 users load your page slowly, the 101st user gets a Connection Refused error. The app crashes.


4. The "Object" Approach (The Industry Standard)

Instead of streaming, we use the "Download and Disconnect" strategy. We create a Java Class (e.g., Student) to act as a container for the data.

The Workflow:

  1. Open Connection: Call the DB.

  2. Fetch: Quickly loop through the ResultSet and copy data into a List<Student>.

  3. Close Connection: Hang up the phone immediately. The DB is now free to serve others.

  4. Display: Pass the List<Student> (which is now safely in RAM) to the JSP/View.

The Trade-off:

  • Cons: We spend a few nanoseconds creating Java Objects.

  • Pros: We save the Database from crashing. We achieve high scalability.


5. The "Search" Efficiency Question

Question: "If we download data to Java, isn't searching a Java List slower than a Database B-Tree?"

The Golden Rule: Filter in DB, Format in Java.

  • Never download 1 million rows to Java to search for "John". That destroys RAM.

  • Always ask the DB to find "John" (WHERE name='John'). The DB uses indexes to find it instantly.

  • Then, download only the result (the 1 or 2 rows found) into Java Objects.


6. The Maintainability Argument (MVC)

Why not use System.out.println() directly in the Servlet? Why the separation?

The "Spaghetti Code" Nightmare:
If you mix SQL logic, Java logic, and HTML design in one file:

  1. You cannot fix a styling error without risking breaking the Database code.

  2. You cannot change the Database (e.g., SQL Server to MySQL) without rewriting the HTML generation logic.

The Solution: Separation of Concerns

  • Model (Student.java): Holds the data.

  • View (JSP): Handles the design (HTML/CSS).

  • Controller (Servlet): Handles the traffic and logic.

We compromise on a tiny bit of computational speed (creating objects) to gain massive Human Speed (easier to read, fix, and maintain code).


7. The Modern Context (React, Angular, Mobile)

Does this still apply if we use React instead of JSP? Yes, even more so.

When sending data to a modern frontend, we send JSON. We need Java Classes (DTOs - Data Transfer Objects) for two reasons:

  1. Translation: Libraries (like Jackson) need a Class to know how to convert data into JSON format { "key": "value" }.

  2. Security (The Filter):

    • Your DB table Users might contain a password column.

    • If you send the raw DB data, you send the password to the hacker's browser.

    • By copying data to a UserDTO class (which doesn't have a password field), you ensure only safe data leaves the server.

Summary Checklist

ConceptWhat it isWhy we handle it this way
ResultSetA live cursor/pointer over a network.We must read it quickly and close it to free up the DB.
Java ClassA container (RAM) for data.It allows us to hold data after the DB connection closes.
SearchingFinding data among millions.Always do this in the DB (SQL), not in Java.
FormattingMaking data pretty (HTML/JSON).Do this in Java/JSP, using the data objects.
The GoalA Scalable App.Minimize the time the DB connection is open.

Comments

Popular posts from this blog

Java Servlets

  According to me its just a translator, who manages the HTTP requests and handle them to the appropriate function of the API. So then, API turns out to be a term or set of those functions which are kept public. Now let us see in little bit of detail what servlets are: For that we need to see few terms: Static Web Pages: Static web pages are the pages, which are already built, and whose content and design always remain the same.  For Example: About us page of some website. Contact info page of some website Dynamic Web Pages: Dynamic pages are not already defined. They are dependent on search queries. For Example: If we search top 5 books, and click on search button, result would be different. If we search top 5 countries and enter search, result would be different.  So, the search result for every search is different. Working: Now if we have to search static page let's say the first page of any website (which is same for every use in every country) then the process is sim...

What is an API? A Simple Explanation for Programming Beginners

API What is an interface? Interface is a control system, through which we can use something. For Example: The interface of car includes: Steering Wheel Brakes Gear Acceleration pedal Mirrors Interface is concerned with the fact that how to use something, rather than how it works. The Easiest Analogy for an API : The Restaurant Imagine you're at a  restaurant . You are the user. You want food (data or a service). You can't just walk into the kitchen and start cooking. That would be  chaotic  and unsafe! Instead, you interact with the  waiter . You look at a  menu  (the  API  documentation) and give your order to the waiter. The waiter takes your request to the kitchen. The kitchen prepares your food. The waiter then brings the response (your delicious meal) back to you. The  waiter  is the contract, the messenger, the interface in our case the  API . They provide a secure and simple way for you to get what you need from the kitchen ...