Java – Recommended Ways to Store Database Information

data structuresjavajdbcjsonMySQL

I am using a Java to connect to MySQL database. I want to iterate through this data and store it into a data structure. This data structure will be

JSON.parse()

and converted from server side to client. Can anyone recommend an appropriate data structure?

The database contains 4 columns. One int, two doubles and another int column, in that order.

I appreciate any input. I just want to make sure I go in the most appropriate direction.

Best Answer

Define a class that contains fields with the appropriate types for the columns in your table and with the same names as they will be represented in your JSON document. The class should contain little or no logic. Such a class is usually called a Data Transfer Object.

You should have another object that loads the data from your database into your DTOs. This is called a Data Mapper (you can use a library for this, eg Hibernate, or do it yourself ... ironically, your code will be simpler to do it yourself).

Another object can convert your DTOs to JSON. Again, you can use a library for this (Jackson is a popular choice, and doesn't tend to introduce complexity like Hibernate does) or do it yourself (perhaps using a library, eg Apache Commons "lang", to escape strings, which is annoyingly tricky to get right).