Database Information & # 8594; object: how to do it?

My application will, upon request, receive information from the database and create an object from this information. I am currently considering two different methods (but I am open to others too!) To accomplish this task:

First method:

class Book { private int id; private String author; private String title; public Book(int id) { ResultSet book = getBookFromDatabaseById(id); this.id = book.id; this.author = book.author; // ... } } 

Method Two:

 public class Book { private HashMap<String, Object> propertyContainer; public Book(int id) { this.propertyContainer = getBookFromDatabaseById(id); } public Object getProperty(String propertyKey) { return this.propertyContainer.get(propertyKey); } } 

With the first method, I find it easier to control, limit, and possibly access properties, add new properties, however, it becomes smoother using method two.

What is the right way to do this?

+4
source share
3 answers

I think that this problem was solved in different ways: ORM, DAO, row and table sorter, many others. No need to repeat it again.

One of the issues worth considering is the interconnection and cyclic dependencies between packages. You may think that you are doing something smart by telling the model object how to persist, but one of the consequences of this choice is the connection between the model objects and the level of conservation. If you do this, you cannot use model objects without perseverance. They really become one big, bulky package. There are no layers.

Another choice is to ensure that model objects do not pay attention to whether they are preserved or not. This is a one-way relationship in this way: perseverance knows about model objects, but not vice versa.

Google for these other solutions. There is no need to beat this dead horse again.

+3
source

The first method will provide you with type safety for related accessories, so that you know what type of object you are returning, and don.t need to be discarded to the type you expect (this becomes more important when providing something other than primitives).

For this reason (plus that it will make the code easier and easier to read), I would choose the first one. In any large applications, you can also quickly, easily and accurately get parameter values ​​back to code for debugging, etc. Inside the object itself.

If someone else will work on this code (or planning to work after you forget about it), the first one will also help you, as you know the parameters, etc. The second will only give you this extensive javadoc.

+1
source

The first is the classic way. The second of them is really impractical.

0
source

Source: https://habr.com/ru/post/1432147/


All Articles