Reputation: 173
Which is the best way to export a JPA query result in a CSV format? I tried opencsv but it wants a java.sql.ResultSet object and I don't understand how to create it. I tried the following code
public ResultSet getAllUsersMap() {
String query = "SELECT p from Participant p ORDER BY p.lastName";
ResultSet rs = (ResultSet) em.createQuery(query).getResultList();
return rs;
}
but I receive the exception java.lang.ClassCastException: java.util.Vector cannot be cast to java.sql.ResultSet
Upvotes: 2
Views: 8653
Reputation: 2112
JPA is an ORM framework spec. It's not directly related to creating CSV files. The error is just saying that you are casting the return value of method getResultList()
to the wrong type.
Using opencsv, something like this should work:
String query = "SELECT p from Participant p ORDER BY p.lastName";
List resultList = em.createQuery(query).getResultList();
BufferedWriter out = new BufferedWriter(new FileWriter("result.csv"));
CSVWriter writer = new CSVWriter(out);
for (Object item : resultList) {
String line = formatParticipantToLine(item) // method to format properties of Participant with comma's
writer.writeNext(item);
}
writer.close();
UPDATE:
You can also use http://opencsv.sourceforge.net/apidocs/au/com/bytecode/opencsv/bean/BeanToCsv.html
with Participant
your bean of course.
Upvotes: 0