Persistencia Blob(Mysql + Primefaces + JSF

0 respostas
denisagui

Olá a todos.
Estou tentando adicionar imagens ao banco utilizando o tipo Blob do mysql, no entanto gostaria de esclarecer algumas duvidas quando a inserção no campo.
métodos utilizados.

ManagedBean

estou utilizando esses dois metodos um para converter em um array de byte[ ] e o outro para fazer o inverso.

public class ArtistaManagedBean {
	private Artista artista;
	private List<Artista> listaArtistas;
	private Artista[] artistasSelect;
	private ArtistaDataModel artistaDataModel;
	private UploadedFile file;
	
	public UploadedFile getFile() {
		ByteArrayInputStream bais = null;
		ObjectInputStream in = null;
		this.file = null;
		
		try {
			bais = new ByteArrayInputStream(getArtista().getImg());
			in = new ObjectInputStream(bais);
			this.file = (UploadedFile) in.readObject();
			in.close();
			
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(file.getFileName()));
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return file;
	}
public class FileUploadController {
	private UploadedFile file;
	private byte[] by;
	
	public byte[] getBy() {
		return by;
	}

	public void setBy(byte[] by) {
		this.by = by;
	}

	public UploadedFile getFile() {
		return file;
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}

	public byte[] serialize(UploadedFile object) {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream out = null;
		byte[] byteObject = null;

		try {
			baos = new ByteArrayOutputStream();
			out = new ObjectOutputStream(baos);
			out.writeObject(object);
			out.close();
			byteObject = baos.toByteArray();

		} catch (Throwable e) {
		}

		return byteObject;
	}

	public void handleFileUpload(FileUploadEvent fileEvent) {
		try {
			setFile(fileEvent.getFile());
			setBy(serialize(getFile()));
			FacesMessage msg = new FacesMessage("Success! Picture is uploaded.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessage msg = new FacesMessage("ERRO! ", "File was NOT loaded");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

	}
}

POJO

@Entity
@Table(name = "artista")
public class Artista implements Serializable {
	private static final long serialVersionUID = 9210163915685834246L;
	private Integer idArtista;
	private String nome;
	private String descricao;
	private byte[] img;
	
	@Lob
	@Column(name = "img")
	public byte[] getImg() {
		return img;
	}
	public void setImg(byte[] img) {		
		this.img = img;
	}

Gostaria de saber como exibir a imagem na pagina, visto que ela não é renderizada utilizando:

xhtml

<p:graphicImage value="#{artistaManagedBean.file}"/>
Criado 18 de maio de 2012
Respostas 0
Participantes 1