Persist field blob with file extension - JPA, Hibernate

Asked

Viewed 903 times

0

I need to persist an attachment as a pdf, xls, etc. (type field blob).

I need to recover this file after persisting it and I don’t want it to be necessary for the user to inform the file extension.

I was directed in another question to create a table only for attachments, which I am not able to do so far. If anyone has suggestions or examples I am grateful.

Table condutor:

CREATE TABLE condutor (
    idCondutor int(11) NOT NULL AUTO_INCREMENT,
    nomeCondutor varchar(255) DEFAULT NULL,
    empresaCondutor int(11) DEFAULT NULL,
    pessoaCondutor int(11) DEFAULT NULL,
    setorCondutor int(11) DEFAULT NULL,
    statusCondutor int(11) DEFAULT NULL,
    PRIMARY KEY (idCondutor),
    KEY FK_sjtsm3daptskn3srw7oq4jahv (empresaCondutor),
    KEY FK_8nfirnssektdhna64ld08p1jg (pessoaCondutor),
    KEY FK_qyu9ky6p3myqq391d62k8aunb (setorCondutor),
    KEY FK_rp36pckj7fhy44mw625xx0494 (statusCondutor),
    CONSTRAINT FK_8nfirnssektdhna64ld08p1jg FOREIGN KEY (pessoaCondutor) REFERENCES pessoa (idPessoa),
    CONSTRAINT FK_qyu9ky6p3myqq391d62k8aunb FOREIGN KEY (setorCondutor) REFERENCES setor (idSetor),
    CONSTRAINT FK_rp36pckj7fhy44mw625xx0494 FOREIGN KEY (statusCondutor) REFERENCES status (idStatus),
    CONSTRAINT FK_sjtsm3daptskn3srw7oq4jahv FOREIGN KEY (empresaCondutor) REFERENCES empresa (idEmpresa)
)

Table condutorinfracao:

CREATE TABLE condutorinfracao (
    idCondInf int(11) NOT NULL AUTO_INCREMENT,
    anexoInfracao longblob,
    valorInfracao decimal(19,2) DEFAULT NULL,
    condutorCondInf int(11) DEFAULT NULL,
    infracaoCondInf int(11) DEFAULT NULL,
    PRIMARY KEY (idCondInf),
    KEY FK_tjm3qu2haonaki7q5u8cb949h (condutorCondInf),
    KEY FK_mcswigv97yisxqakgleui6168 (infracaoCondInf),
    CONSTRAINT FK_mcswigv97yisxqakgleui6168 FOREIGN KEY (infracaoCondInf) REFERENCES infracao (idInfracao),
    CONSTRAINT FK_tjm3qu2haonaki7q5u8cb949h FOREIGN KEY (condutorCondInf) REFERENCES condutor (idCondutor)
)

Entity Condutor:

public class Condutor implements EntidadeBase, Serializable {

    @Id
    @Basic(optional = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idCondutor")
    private Integer id;

    @Column(name = "nomeCondutor")
    private String nome;

    @ManyToOne
    @JoinColumn(name = "setorCondutor")
    private Setor setor;

    @ManyToOne
    @JoinColumn(name = "pessoaCondutor")
    private Pessoa pessoa;

    @ManyToOne
    @JoinColumn(name = "empresaCondutor")
    private Empresa empresa;

    @ManyToOne
    @JoinColumn(name = "statusCondutor")
    private Status status;

    @OneToMany(mappedBy = "condutor", cascade = CascadeType.ALL)
    private List<CondutorInfracao> condInfracoes;

    //getters e setters

}

Entity CondutorInfracao:

public class CondutorInfracao implements Serializable, EntidadeBase {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idCondInf")
    private Integer id;

    @Column(name = "valorInfracao")
    BigDecimal valor_infracao;

    @Lob
    @Column(name = "anexoInfracao")
    private byte[] anexo;

    @ManyToOne
    @JoinColumn(name = "condutorCondInf", referencedColumnName = "idCondutor")
    private Condutor condutor;

    // getters e setters

}

Save:

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    CondutorInfracao condutorInfracao = new CondutorInfracao();
    condutorInfracao.setCondutor((Condutor) jCCondutor.getSelectedItem());
    condutorInfracao.setInfracao((Infracao) jCInfracaoDescr.getSelectedItem());

    Locale brasil = new Locale("pt", "BR");
    NumberFormat nf = NumberFormat.getCurrencyInstance(brasil);
    String str = valorField.getText();
    Number str2 = null;
    try {
        str2 = nf.parse(str);
    } catch (ParseException ex) {
        Logger.getLogger(CondutorInfracaoView.class.getName()).log(Level.SEVERE, null, ex);
    }
    BigDecimal bd = new BigDecimal(str2.doubleValue());
    BigDecimal ajusted = bd.setScale(nf.getMaximumFractionDigits(), BigDecimal.ROUND_HALF_UP);
    condutorInfracao.setValor_infracao(ajusted);
    try {
        String path = caminho;
        FileInputStream input = null;
        File theFile = new File(path);
        input = new FileInputStream(theFile);
        byte[] bytes = IOUtils.toByteArray(input);
        condutorInfracao.setAnexo(bytes);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Não foi possível anexar o arquivo!");
    }
    try {
        CondutorInfracaoDao ci = new CondutorInfracaoDao();
        ci.save(condutorInfracao);
        JOptionPane.showMessageDialog(null, "Gravado !");
        modelo.limpaLista();
        preencherTabela();
    } catch (Exception erro) {
        JOptionPane.showMessageDialog(null, "Erro na Gravação:" + erro);
    }

    refresh();
}
  • 1

    Rodrigo, as it stands you can only include a new attribute to CondutorInfracao, which would be the file extension, no?

  • Yes, that way I can, when I attach the arquivo, is displayed in a JTextField the name followed by the extension. I did not run this test. At first I would try with a new table only with files.

  • When I click the recover button, open the JFileChooser, after inserting the name of arquivo, by clicking open, this is already saved, so would have to somehow in this click, in the open button, already concatenate with the extension? Something in this sense?

  • A question you should have asked before, as this project is for learning purposes, it is necessary to create a new table only for files, under what circumstances it would be?

  • If you want to save the extension and you have the file name, there is no difficulty in that. The previous suggestion of having a separate entity is by mere organization in contexts that N entities relate to attachments.

No answers

Browser other questions tagged

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