There is a simple web application that includes several servlets, each of which connects to a database, creates a model and displays it through jsp. I would like to optimize work with the database by working with Java objects instead of tables. For example, if you need to get a bus with a specific id from the bus table, instead of connecting the database, we get the bus object from the hash table, which will work many times faster.

I thought of implementing this way: save the data in the tables. B. in objects at the first connection, then work with these objects, and in the case of a change in b.d. change objects and tables.

I do not know how to create such a class "database", which would store all the data without being deleted from memory when the servlet is finished. I would like to know how this can be done. Thank you in advance.

  • one
    Look in the direction of ORM, maybe it will suit you. - post_zeew
  • one
    why do you need acceleration? did you measure the load and realized that the current architecture is not coping? - Mikhail Vaysman
  • one
    ORM standard promoted by JavaEE - JPA en.wikibooks.org/wiki/Java_Persistence . The most famous representatives are: EclipseLink (exemplary implementation), Hibernate. JPA is part of the JavaEE Web Profile, so it must be available immediately out of the box in any application server. There are also opposing confederations, for example JDO. And the same Hibertate appeared long before the JPA and can work both as JPA and in its own way. Everyone knows how to use connection pooling, cache query results in several levels, if performance is so concerned. - Sergey

1 answer 1

The pattern is called a Data Access Object or simply DAO. You write a class that encapsulates work with the database inside. For example, BusDao, which has a byId method that returns a Bus object. You can also write a bunch of similar methods (byName, byModel, etc.)

Inside BusDao, you can store the received data in a "self-made" cache based on a HashMap, for example. Here it is necessary to be confused with the key, so that it is unique for each object.

Accordingly, in order for the data to "walk" from servlet to servlet, our DAO must also be singleton (also such a pattern).

That's all, no magic)

But as noted in the comments, you can try to use any ORM (Hibernate, Ebean, thousands of them ). In life, it is useful, because there are no projects that do not use them when working with a database.