开发者

Java: Storing information from database. What collections are appropriate?

I write an application in Java. I get form a database a table (clients) which contains fields like:

name | surname | adress

What is the best solution to store this data in my app? Should I create an object for each client and store these objects in a list or set?

The table contains about 100 records and it's alrea开发者_运维问答dy sorted. Thanks in advance.


The most straightforward way is to create a class that contains fields that correspond to your database columns (name, surname, address). Then, as you already say yourself, create an instance of this class for each row in the table and store them in a List.

A Set will not be appropriate, since most Set implementations (for example HashSet) are not ordered, so if your data is sorted, the Set won't preserve the sort order. A List is ordered.

To get the data out of the database, you could simply program it in JDBC yourself, which is straightforward in this case: open a connection to the database, execute an SQL query, loop through the rows in the ResultSet, create an object for each row and fill it with the data that you get from the ResultSet, store the created objects in a List.

When your data model becomes more complicated than a single class, it might be worth it to use an object-relational mapping (ORM) framework. Java has a standard API for this, Java Persistence API (JPA). Hibernate is a popular implementation of this API.


While Hibernate may be overkill for what you're doing, you may still want to check it out. If you're going to end up doing much more than retrieval, it may be worth investing a bit of time into (it may save you a ton of work later).

Depending on what you're doing with the records, you could leave them in your recordset, iterate over them and do whatever you want with them. If you need to do some work with them, then yes, put each one in an object and put those objects into a collection of some type (ArrayList will keep them sorted for you).


You should create a class for the object and then have a list of objects, each corresponding to one table record.

If you're going to be doing tasks like this often, I would suggest using a tool such as Hibernate to make this easy and automated, so you don't always have to manually create and fill the classes and interact with the database yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜