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...

OnClick and {}

1. The onClick Mystery: Is it the same? Yes, the concept is 90% the same. If you know how to handle a click in plain HTML/JavaScript, you already know how to do it in React. The logic flow is identical: Event: A user does something (Click). Listener: The element hears it ( onClick ). Handler: A specific function runs to deal with it. The "React Twist" (The 10% difference): There are two tiny syntax differences you must memorize: CamelCase: In HTML, it is onclick (lowercase). In React, it is onClick (camelCase). Function, not String: HTML (Old): onclick="doSomething()" (A string of code). React (New): onClick={doSomething} (Passing the actual function itself). So yes, your intuition is correct: Whenever you need to handle logic (clicks, hovers, typing), you will stick to this pattern: on[Event]={functionName} . 2. The Curly Braces { } : The Portal This is the most important syntax rule in JSX. Imagine your code file has two "Modes": HTML Mode: W...

Servlet Context and Servlet Config

  Problem without init-parameters? Imagine you write a servlet that connects to a database. If you write the database URL, username, and password directly in your Java code, you have a big problem: What if the database password changes? You have to find the code, change it, recompile the .java file into a .class file, and redeploy the entire application. What if you want to use the same servlet in a different project with a different database? You can't. The code is stuck with the old settings. This is where init parameters come in. They let you move this configuration data out of your code and into the deployment descriptor ( web.xml file). How init-parameters help when we use them in web.xml file? They help us in a way that we don't have to find that particular part of code to change it. And also, it saves us the hectic of changing source code and recompiling that again. Anyone with .war file can change the web.xml file  and use it with class file without having the ne...