Class Database

java.lang.Object
tutorial.persistence.Database

public final class Database extends Object
This class is a static facade for persistence operations. All methods are static, so it can be statically imported in client classes for maximum usability.

All of the persistence operations made available through this facade access a thread-bound persistence context. In this particular implementation, the standard JPA API is used, where jakarta.persistence.EntityManager represents a work unit. Typically, each work unit instance exists only long enough to perform a single database transaction. Transaction demarcation is not a responsibility of this class, however, which simply keeps the association between the current thread and a dedicated work unit object (an EntityManager instance). (In a web app, the persistence context can be tied to the HTTP request/response cycle, which normally runs entirely in a single thread for each request/response pair; a central action-dispatch servlet can commit or rollback the current transaction, while a custom jakarta.servlet.Filter can close the thread-bound EntityManager.)

Compared to direct use of an ORM API such as JPA, or to the use of Data Access Objects (the "DAO" pattern), this static persistence facade pattern has several advantages. Mainly, client code which needs to perform high-level persistence operations (such as persisting a new entity instance, deleting an already persisted entity, or finding and loading persistent entities) tends to be simpler and shorter. In the case of entity-specific DAO classes, potentially thousands of lines of code are saved, without any real loss in portability (the facade implementation can adapt to new versions of the ORM API or even a different ORM API; and consider that switching between an ORM API and plain use of JDBC is not viable anyway, since with JDBC the DAO classes need to expose methods for the execution of "UPDATE" statements, which are not needed with modern ORM APIs).

  • Method Details

    • find

      public static <E> E find(Class<E> entityClass, Object entityId)
    • find

      public static <E> List<E> find(String ql, Object... args)
    • persist

      public static void persist(Object data)
    • remove

      public static void remove(Object persistentEntity)