0
I’m with a JSF project with the DAO model using Hibernate, and I’m having a hard time understanding how to save the image in the database.
I would just need to know what the method would look like to save an image in a DAO class and how it would look in the Bean class.
I found this video: https://www.youtube.com/watch?v=2b3KQApdOAU
This one got closer than he needed: http://www.guj.com.br/39230-jsf2---upload-de-imagens
This was a repository I found: https://github.com/wladyband/fileupload
This is the project I’m working for: https://github.com/wladyband/Drogaria/tree/master/Drogaria
And that’s the class I want to introduce: https://github.com/wladyband/Drogaria/blob/master/Drogaria/src/br/com/drogaria/domain/Produto.java
package br.com.drogaria.domain;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name = "tbl_produtos")
@NamedQueries({
    @NamedQuery(name = "Produto.listar", query = "SELECT p from Produto p"),
    @NamedQuery(name = "Produto.buscarPorCodigo", query = "SELECT p from Produto p where p.codigo = :codigo") })
public class Produto {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "pro_codigo")
    private Long codigo;
    @NotEmpty(message="O campo descrição é obrigatório")
    @Size(min=5,max=50, message="Tamanho invalido para o campo (5 - 50)")
    @Column(name = "pro_descricao", length = 50, nullable = false)
    private String descricao;
    @NotNull(message="O campo é obrigatório")
    @DecimalMin(value="0.0", message="Informe um valor ou igual a zero para o campo preço")
    @DecimalMax(value="99999.99", message="Informe um valor menor que 100 mil para o campo preço")
    @Column(name = "pro_preco", precision = 7, scale = 2, nullable = false)
    private BigDecimal preco;
    @NotNull(message="O campo é obrigatório")
    @Min(value = 0, message="Informe um valor maior ou igual a zero para o campo quantidade")
    @Max(value = 9999, message="Informe um valor menor ou igual a 9999 para o campo quantidade")
    @Column(name = "pro_quantidade", nullable = false)
    private Integer quantidade;
    @NotNull(message="O campo fabricante é obrigatório")
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "tbl_fabrincantes_fab_codigo", referencedColumnName = "fab_codigo", nullable = false)
    private Fabricante fabricante;
    public Long getCodigo() {
        return codigo;
    }
    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }
    public String getDescricao() {
        return descricao;
    }
    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }
    public BigDecimal getPreco() {
        return preco;
    }
    public void setPreco(BigDecimal preco) {
        this.preco = preco;
    }
    public Integer getQuantidade() {
        return quantidade;
    }
    public void setQuantidade(Integer quantidade) {
        this.quantidade = quantidade;
    }
    public Fabricante getFabricante() {
        return fabricante;
    }
    public void setFabricante(Fabricante fabricante) {
        this.fabricante = fabricante;
    }
    @Override
    public String toString() {
        return "Produto [codigo=" + codigo + ", descricao=" + descricao
                + ", preco=" + preco + ", quantidade=" + quantidade
                + ", fabricante=" + fabricante + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Produto other = (Produto) obj;
        if (codigo == null) {
            if (other.codigo != null)
                return false;
        } else if (!codigo.equals(other.codigo))
            return false;
        return true;
    }
}
The GUJ website helped me a little with this post, and I still can’t solve my problem.
http://www.guj.com.br/39728-como-gravar-imagens-na-base-de-dados-em-jsf
I know the way to do it is similar to this model below, I just need to know how to adapt this model to my project.
@ManagedBean(name = "fileUploadMB")
@RequestScoped
public class fileUploadMB {
    public static byte[] arquivo;
    public static String nomeArquivo;
    private Ouvidoria ouvidoriaCadastro;
    public Ouvidoria getOuvidoriaCadastro() {
        if (ouvidoriaCadastro == null) {
            ouvidoriaCadastro = new Ouvidoria();
        }
        return ouvidoriaCadastro;
    }
    public void setOuvidoriaCadastro(Ouvidoria ouvidoriaCadastro) {
        this.ouvidoriaCadastro = ouvidoriaCadastro;
    }
    /* Método que faz o Upload dos arquivos */
    public void doUpload(FileUploadEvent fileUploadEvent) throws IOException {
        UploadedFile uploadedFile = fileUploadEvent.getFile();
        String fileNameUploaded = uploadedFile.getFileName();
        long fileSizeUploaded = uploadedFile.getSize();
        System.out.println(uploadedFile);
        // arquivo = uploadedFile.getContents();
        String infoAboutFile = "<br/> Arquivo recebido: <b>" + fileNameUploaded
                + "</b><br/>" + "Tamanho do Arquivo: <b>" + fileSizeUploaded
                + "</b>";
        //Mensagem exibida na tela
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.addMessage(null,
                new FacesMessage("Sucesso", infoAboutFile));
        arquivo = (IOUtils.toByteArray(uploadedFile.getInputstream()));
        nomeArquivo = uploadedFile.getFileName();
        ouvidoriaCadastro.setArquivo(arquivo);
        ouvidoriaCadastro.setNomeArquivo(fileNameUploaded);
        ouvidoriaCadastro.setNomeArquivo(nomeArquivo);
        System.out.println("Arquivo capturado" + arquivo);
        System.out.println("Nome do Arquivo" + nomeArquivo);
    }
}
Page:
<p:outputLabel value="Selecione um Arquivo(Opcional):" />
<p:fileUpload fileUploadListener="#{fileUploadMB.doUpload}"
    mode="advanced" showButtons="false" label="Enviar Arquvios.." auto="true" />
						
What would be necessary to avoid the duplicate?
– wladyband
You can edit your question including the details of this question, since it is the same. To edit the other question, access this link: Edit How to Save Image to Database with JSF2. After this, consider removing this question.
– Bruno César
I’m sorry, I don’t understand.
– wladyband