I'm writing a web application using Spring/Hibernate that displays a report to a user, I would like to allow the user to export the results to a CSV file.
Can anyone suggest an efficient way to output Hibernate query results to a CSV file?
Thanks!
I'm writing a web application using Spring/Hibernate that displays a report to a user, I would like to allow the user to export the results to a CSV file.
Can anyone suggest an efficient way to output Hibernate query results to a CSV file?
Thanks!
If you are using Hibernate the result of your query will be a list of objects, I would iterate over the list and print those objects as csv to a StringBuffer using a Utility class.
Having Hibernate instantiate a (big?) list of objects and their dependencies just to serialize them to string data right after instantiation is of course not very efficient from a clock-cycles-and-RAM viewpoint, it might however be so from a developer-hours viewpoint. If you are concerned about your processor and RAM I'd suggest running a plain JDBC SQL query and process that directly to csv.
Hibernate is for object-relational mapping. If you don't have objects on the other end, what's the point?
Spring doesn't prohibit mixing and matching JDBC and Hibernate. Use the best approach for the problem at hand. Straight JDBC sounds best in your case.
Also, have a look at Spring's AbstractJExcelView if this is a web app. Perhaps you can write a straight DAO to get the data, send it back to the controller, and have it render a JExcelView back to the browser. The user will see the data as an Excel spreadsheet in the browser. They will have the option of saving it as a .csv file from the browser. Nice and clean.
I suppose Hibernate is being used here as part of a larger application and one part of that is exporting something to CSV. It may not be proper to use JDBC for this one piece while Hibernate is being used across the application.
If my assumption is not correct, then JDBC is the right choice, otherwise you may want to iterate over Hibernate's collections to build your CSV.
Sometimes there are a few irritants in building CSV's, such as having double quotes in a column value, other such things. Here is a good library that might help you: