# Eo / Ejb / Example

The `eo.ejb.example` package is a demonstration subpackage within the EJB (Enterprise JavaBeans) module. It contains a JPA entity for database mapping and a utility class showcasing a common reflection-based instantiation pattern.

## Overview

This package serves as an example of two key Java EE/JPA patterns: persistent entity modeling via JPA annotations, and dynamic class loading using reflection. The [`EntityClass`](EntityClass.java) class demonstrates how to map a Java object to a relational database table, while [`PatternOneVar`](PatternOneVar.java) illustrates how to load and instantiate arbitrary classes by their fully-qualified name at runtime.

## Key Classes and Interfaces

### [`EntityClass`](EntityClass.java)

`EntityClass` is a JPA entity that maps to the `entity_class` database table. It is annotated with `@Entity` and `@Table(name = "entity_class")`, making it a fully managed persistence object.

**Purpose:** This class represents a simple data record with two fields — an identifier and a name. It demonstrates the minimal structure needed for a JPA-managed entity in an EJB context.

**Fields:**

| Field | Type | Database Column | Description |
|-------|------|-----------------|-------------|
| `id` | `Long` | (primary key) | The unique identifier for the entity, marked with `@Id`. |
| `name` | `String` | `item_name` | The displayable name, stored in a column named `item_name`. |

**Key methods:**

- `getId()` — Returns the entity's unique `Long` identifier. This accessor is used by JPA providers and application code to reference the entity by its primary key.
- `getName()` — Returns the `String` name stored for this entity. This is the human-readable value for the record.

**Design notes:** The class provides getters but no setters, which means it is effectively read-only from outside the class. In JPA, this pattern is valid for entities where mutations happen through the persistence context rather than direct field assignment. The entity is minimal — it has no constructor logic, no validation, and no business behavior beyond data storage.

### [`PatternOneVar`](PatternOneVar.java)

`PatternOneVar` demonstrates the "One Variable" pattern — a Java coding convention where a single variable is reused to reference objects of different types. In this case, the variable `obj` is of type `Object` and holds an instance created from a class name provided at runtime.

**Purpose:** This class shows how to dynamically load and instantiate a class given its fully-qualified name as a string. It uses `Class.forName(clsName).newInstance()` to perform runtime reflection-based object creation.

**Key method:**

- `load(String clsName)` — Accepts a fully-qualified class name as a `String`, loads the class via `Class.forName()`, creates a new instance using `newInstance()`, and prints the result to `System.out`.

  **Parameters:**
  - `clsName` — The fully-qualified name of the class to load and instantiate (e.g., `"com.example.MyClass"`).

  **Returns:** `void`.

  **Side effects:** The instantiated object is printed to standard output. The method throws `Exception`, which includes any of `ClassNotFoundException`, `InstantiationException`, or `IllegalAccessException` that `Class.forName()` and `newInstance()` may propagate.

  **Design notes:** This is a reflection-based pattern. It allows the application to instantiate classes whose types are not known at compile time — for example, when loading plugin classes, configuration-driven implementations, or third-party libraries. The broad `Exception` throw and the use of `Object` as the variable type are hallmarks of the "One Variable" anti-pattern that modern Java typically avoids through generics and proper type handling, but it remains a common and useful technique in flexible, plugin-style architectures.

## How It Works

### Entity lifecycle (EntityClass)

1. A JPA provider (such as Hibernate, EclipseLink, or the container's built-in persistence unit) scans the classpath for classes annotated with `@Entity`.
2. Upon finding `EntityClass`, it registers it with the persistence unit and creates or expects an `entity_class` table in the database.
3. The `id` field is treated as the primary key. The `name` field maps to the `item_name` column.
4. Application code (or EJB session beans in the broader system) creates, reads, updates, and deletes `EntityClass` instances through the JPA `EntityManager`.

### Dynamic class loading (PatternOneVar)

1. Code calls `PatternOneVar.load("com.example.SomeClass")`.
2. `Class.forName("com.example.SomeClass")` loads the class definition from the classpath.
3. `.newInstance()` invokes the class's no-arg constructor to create an instance.
4. The resulting object is cast to `Object` and printed via `System.out.println()`.

This pattern is useful when the class to instantiate is determined at runtime (from configuration, user input, or plugin discovery) rather than known at compile time.

## Data Model

`EntityClass` defines a simple two-column data model:

```
+-------------------+
|  entity_class     |
+-------------------+
| id      (PK, Long)|  ← primary key
| name    (String)  |  ← mapped to column "item_name"
+-------------------+
```

The table is named `entity_class` (explicitly set via `@Table`). The `id` column is implicitly named `id` (matching the field name), and the `name` field is explicitly mapped to the column `item_name`.

## Dependencies and Integration

This package uses the following external APIs:

- **JPA (`javax.persistence`)** — `EntityClass` depends on JPA annotations (`@Entity`, `@Table`, `@Id`, `@Column`) to integrate with a persistence provider. This ties the package to the Java EE / Jakarta EE runtime.
- **Reflection (`java.lang.Class`)** — `PatternOneVar` uses the standard Java reflection API to dynamically load classes. This is a core JRE dependency with no external libraries required.

There are no inter-package or cross-module dependencies from this package based on the current index.

```mermaid
flowchart LR
    PKG["Package: eo.ejb.example"]

    subgraph ENTITIES["Entities"]
        EC["EntityClass"]
    end

    subgraph PATTERNS["Patterns"]
        PV["PatternOneVar"]
    end

    PKG --> EC
    PKG --> PV
    EC -. "reflection target" .-> PV
```

## Notes for Developers

- **Read-only entity:** `EntityClass` has no setters. If you need to modify its fields, you will need to either add setters or mutate through the JPA `EntityManager`.
- **Reflection safety:** `PatternOneVar.load()` throws a broad `Exception`. Callers should catch `ClassNotFoundException` (class not on classpath), `InstantiationException` (class has no no-arg constructor), and `IllegalAccessException` (constructor is not accessible) specifically rather than swallowing the generic `Exception`.
- **`Class.forName(clsName).newInstance()` deprecation:** The `newInstance()` method on `Class` has been deprecated since Java 9. In modern Java, prefer `cls.getDeclaredConstructor().newInstance()` for the same behavior without the deprecation warning.
- **EntityClass is minimal:** This entity has no timestamps, no relationships (`@OneToMany`, `@ManyToOne`, etc.), and no embedded objects. It is intended as an example, not a production-ready data model.
