How to save a csv using hibernate and mysql [closed]

0

I need to do the following routine:

  • Read some information from the database;
  • Generate a csv based on this data;
  • Save this csv to the database;
  • 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. Define the field in the database as BLOB and in the entity as byte[]; How do I convert the object FileWriter to byte?

    Regarding item 4, I intend to use p:fileDownload of Primefaces. However it expects a StreamedContent , that is. I'll have to do a new conversion!

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

        
    asked by anonymous 12.07.2017 / 16:00

    1 answer

    2

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

  • Generate csv using the StringBuilder. Example:

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

    ExportData exportData = new ExportData();
    exportData.setFile(csv.toString().getBytes());
    
  • Retrieve the information in the database and convert to StreamedContent.

    private StreamedContent file;
    
    file = new DefaultStreamedContent(new ByteArrayInputStream(exportDataService.exportData()), "csv", "export.csv");
    
  • It generates the gets and sets of the file, to be able to get in xhtml.

  • Insert a commandButton with fileDownload, using 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>
    
  • 13.07.2017 / 19:31