Question

For now I have a CSV with several columns in rows. Eventually, I will have a SQL relational database structure. I was wondering if there are any libraries to easily extract this data into a list of java objects.

Example:

title | location | date
EventA | los angeles, ca | 05-29-2014
EventB | New York, NY | 08-23-2013

This is the structure of the data in csv. I would have a java object called Event:

Event(String title, String location, String Date)

I am aware of openCSV. Is that would I need to use for csv? If that is the case, what is the different solution for a SQL relational database?

Also, does can reading a csv only be done in the main method?

Was it helpful?

Solution

For when you convert to the SQL database, you can use Apache's dbutils for a low-level solution, or Hibernate for a high-level solution.

dbutils You can implement a ResultSetHandler to convert a result set into an object or if its a POJO the framework can convert it for you. There are examples on the apache site. http://commons.apache.org/proper/commons-dbutils/

Hibernate There are plenty of tutorials out there for working with Hibernate. http://www.hibernate.org/

OTHER TIPS

Try JSefa, which allows you to annotate Java classes that can be used in a serialization and de-serialization process.

From the tutorial:

The annotations for CSV are similar to the XML ones.

@CsvDataType()
public class Person {
    @CsvField(pos = 1)
    String name;

    @CsvField(pos = 2, format = "dd.MM.yyyy")
    Date   birthDate;
}

Serialization

Serializer serializer = CsvIOFactory.createFactory(Person.class).createSerializer();

This time we used the super interface Serializer, so that we can abstract from the choosen format type (XML, CSV, FLR) in the following code.

The next should be no surprise:

serializer.open(writer);
// call serializer.write for every object to serialize
serializer.close(true);

The result

Erwin Schmidt;23.05.1964

Thomas Stumm;12.03.1979

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top