How to save a csv using Hibernate and mysql

Asked

Viewed 136 times

0

I need the following routine to be done:

  1. Read some information from the database;
  2. Generate a csv based on this data;
  3. Write this csv to the database;
  4. Start downloading this file to the user.

I was able to do items 1 and 2, generating the file as follows:

FileWriter writer = new FileWriter("c:\\test.csv");
writer.append("user");
writer.flush();
writer.close();

Going to item 3. I set the field in the database as BLOB and in the entity as byte[]; How do I convert the object FileWriter for byte?

Regarding item 4 I intend to use the p:fileDownload of the Primefaces. But the same awaits a StreamedContent, ie. I will have to perform a new conversion!

I may be wrong in some of these notes. And I ask for everyone’s help to solve this problem!

  • 1

    Limit the question to a specific problem and provide sufficient detail to get an adequate answer.

  • Thanks for the editing. You think I should provide more than to get an adequate response?

1 answer

2


After several queries on the internet. I managed to find a solution...

  1. Generate csv using Stringbuilder. Example:

    StringBuilder csv = new StringBuilder();
    csv.append("USER");
    
  2. Save csv to your mapped entity (remembering that the type of the entity field must be byte[] and in the database must be BLOB.

    ExportData exportData = new ExportData();
    exportData.setFile(csv.toString().getBytes());
    
  3. Retrieve the information in the bank and convert to Streamedcontent.

    private StreamedContent file;
    
    file = new DefaultStreamedContent(new ByteArrayInputStream(exportDataService.exportData()), "csv", "export.csv");
    
  4. Generates the gets and sets of the file, to be able to obtain in xhtml.

  5. Insert a commandButton with fileDownload using the actionListener. If you try to use the action the value will only be populated after the second iteration.

    <p:commandButton value="Export Data" ajax="false"
                     actionListener="#{listaExportMB.exportData()}"                                       
                     styleClass="btn-info"
                     icon="fa fa-cloud-download">
        <p:fileDownload value="#{listaExportMB.file}"/>                         
    </p:commandButton>
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.