Multilayer architecture

A multilayer architecture (also called n-tier architecture) is a way to structure an application into separate layers, each with a specific responsibility. This improves maintainability, scalability, and separation of concerns.

Common Layers in Multilayer Architecture:

  1. Presentation Layer (UI Layer)
    • Handles user interaction (e.g., web pages, desktop GUI).
    • Example: JSP, Servlets, JavaFX, Swing.
  2. Business Logic Layer (Service Layer)
    • Contains the core business rules and logic.
    • Example: Java classes performing calculations, validations, or orchestrating workflows.
  3. Data Access Layer (DAO Layer)
    • Manages database access.
    • Example: JDBC, JPA, Hibernate classes interacting with the database.
  4. Database Layer
    • The actual database storing data (e.g., MySQL, PostgreSQL).

Example in Java

Scenario: Simple application to manage users.

1. Database Layer

Assume we have a table users with id, name, email.

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    email VARCHAR(50)
);

2. Data Access Layer (DAO)

// User.java (Model)
public class User {
    private int id;
    private String name;
    private String email;

    // Constructors, getters, setters
    public User(int id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    public int getId() { return id; }
    public String getName() { return name; }
    public String getEmail() { return email; }
}
// UserDao.java (Data Access Layer)
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private Connection connection;

    public UserDao(Connection connection) {
        this.connection = connection;
    }

    public void addUser(User user) throws SQLException {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, user.getName());
            stmt.setString(2, user.getEmail());
            stmt.executeUpdate();
        }
    }

    public List<User> getAllUsers() throws SQLException {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM users";
        try (Statement stmt = connection.createStatement()) {
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                users.add(new User(rs.getInt("id"), rs.getString("name"), rs.getString("email")));
            }
        }
        return users;
    }
}

3. Business Logic Layer (Service)

// UserService.java (Business Layer)
import java.sql.SQLException;
import java.util.List;

public class UserService {
    private UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public void registerUser(String name, String email) throws SQLException {
        if (name == null || email == null) {
            throw new IllegalArgumentException("Name and email cannot be null");
        }
        User user = new User(0, name, email);
        userDao.addUser(user);
    }

    public List<User> listUsers() throws SQLException {
        return userDao.getAllUsers();
    }
}

4. Presentation Layer (Main Application)

// MainApp.java (Presentation Layer)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class MainApp {
    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb", "root", "password")) {

            UserDao userDao = new UserDao(connection);
            UserService userService = new UserService(userDao);

            // Add user
            userService.registerUser("Alice", "alice@example.com");
            userService.registerUser("Bob", "bob@example.com");

            // List users
            List<User> users = userService.listUsers();
            for (User u : users) {
                System.out.println(u.getId() + " " + u.getName() + " " + u.getEmail());
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

✅ Explanation of Layers in the Example:

  • Presentation Layer: MainApp → interacts with the user.
  • Business Layer: UserService → enforces rules, validations.
  • Data Access Layer: UserDao → interacts with the database.
  • Database Layer: MySQL table users.

This separation ensures that if the database or UI changes, you only need to update one layer, not the entire application.

Leave a Reply