Java – How would you transfer data between your data structures and databases

cdata structuresdatabasejava

I'm learning programming in school and I have this question that's bugging me about data structures and transferring the information stored inside them to databases. We're doing just small systems – registration for an event, point of sale for a local restaurant, sales and inventory, etc

Let's say someone registers himself, should it be passed into a data structure and then into the database, or should it just be transferred directly to the database?

Best Answer

At its most basic, what you need to develop to transfer data between data structures in memory and persistent data stores (files, DB, whatever) is a Data Access Layer or DAL. This is one of your "application tiers" in a properly-constructed N-tier application. Objects in this tier know how to create data structures from DB data, and conversely to convert a properly-populated data structure into DB data, so that objects generally lying outside this tier don't have to have this knowledge.

There are several models for building a DAL tier. The most common in my experience is a centralized "front door" that can accept any request to read or write data and produce any needed data structure. This pattern is called the "Repository". You would make a call to this object along the lines of:

int myObjectId = 1243;
MyObject myObjectInstance = myRepository.RetrieveById<MyObject>(myObjectId);

... and then myObjectInstance would be populated with the data from the table representing MyObject records, with the identifying key that we specified. How that happens exactly, nobody outside the Repository really has to know; you could dynamically construct a SQL statement, use a Data Access Object that knows specifically how to retrieve MyObject instances, or you could do as Oded states and use a third-party library called an Object-Relational Mapper or ORM which abstracts away all the details of how the retrieval happens.

Related Topic