Hebert_Coelho 24 de fev. de 2012
Como você está fazendo no JPA?
e_novaski 24 de fev. de 2012
estou utilizando dessa forma
public void gravarArquivo () throws FileNotFoundException {
FileInputStream fis = null ;
File file = new File ( "myPhoto.png" );
fis = new FileInputStream ( file );
projetoDocumento . setArquivo ( setbina );
FacesContext context = FacesContext . getCurrentInstance ();
boolean resultado = dao . gravarArquivo ( projetoDocumento );
if ( resultado ) {
context . addMessage ( null , new FacesMessage ( "Registro salvo com sucesso!" ));
} else {
context . addMessage ( null , new FacesMessage ( "Erro ao salvar o registro!" ));
}
}
arquivo gravar dao
public boolean gravarArquivo ( ProjetoDocumento projetoDocumento ) {
boolean sucesso = false ;
try {
emArquivo . merge ( projetoDocumento );
sucesso = true ;
} catch ( Exception e ) {
e . getMessage ();
}
return sucesso ;
}
variaveis
private static final long serialVersionUID = 1 L ;
@EmbeddedId
protected ProjetoDocumentoPK projetoDocumentoPK ;
private String arquivo ;
private String tipo ;
Hebert_Coelho 24 de fev. de 2012
Você está passado o arquivo para dentro de uma string?
private String arquivo;
Olha esse post aqui como fazer:
https://blogs.oracle.com/adf/entry/using_jpa_to_insert_and_retrieve_clob_and_blob_types
e_novaski 24 de fev. de 2012
blz… eu vou dah uma lida nesse post valeu…
e_novaski 25 de fev. de 2012
Bom dia, jakefrog
eu nao consegui achar a classe IOManager e dai o link do exemplo nao funciona vc poderia me dah mais essa forca
IOManager manager=new IOManager();
Hebert_Coelho 25 de fev. de 2012
Pelo que eu entendi isso aí é uma classe que você teria que criar para tratar as informações.
O post é mesmo para mostrar como mapear para JPA.
e_novaski 25 de fev. de 2012
Nao querendo abusar mas vc teria um exemplo pratico para isso?
grato.
alexandergtk 25 de fev. de 2012
boa tarde amigos, faz um tempo que to tentando fazer isso mas fico empacado em alguns conceitos.
eu fiz dessa forma talvez possam me ajudar.
meu beans
@Entity
@Table ( name = "anexo" )
@NamedQueries ({
@NamedQuery ( name = "Anexo.findAll" , query = "SELECT a FROM Anexo a" )})
public class Anexo implements Serializable {
private static final long serialVersionUID = 1L ;
@Id
@Column ( name = "anexo_id" , nullable = false )
@SequenceGenerator ( name = "Anexo_Generator" , sequenceName = "anexo_sequence" , allocationSize = 1 )
@GeneratedValue ( strategy = GenerationType . SEQUENCE , generator = "Anexo_Generator" )
@Basic ( optional = false )
@NotNull
private Integer anexoId ;
@Basic ( optional = false )
@NotNull
@Size ( min = 1 , max = 255 )
@Column ( name = "caminho" , nullable = false , length = 255 )
private String caminho ;
@Basic ( optional = false )
@NotNull
@Size ( min = 1 , max = 255 )
@Column ( name = "nome" , nullable = false , length = 255 )
private String nome ;
@Basic ( optional = false )
@NotNull
@Lob
@Column ( name = "arquivo" , nullable = false )
private byte [] arquivo ;
public Anexo () {
}
public Anexo ( Integer anexoId ) {
this . anexoId = anexoId ;
}
public Anexo ( Integer anexoId , String caminho , String nome , byte [] arquivo ) {
this . anexoId = anexoId ;
this . caminho = caminho ;
this . nome = nome ;
this . arquivo = arquivo ;
}
public Integer getAnexoId () {
return anexoId ;
}
public void setAnexoId ( Integer anexoId ) {
this . anexoId = anexoId ;
}
public String getCaminho () {
return caminho ;
}
public void setCaminho ( String caminho ) {
this . caminho = caminho ;
}
public String getNome () {
return nome ;
}
public void setNome ( String nome ) {
this . nome = nome ;
}
public byte [] getArquivo () {
return arquivo ;
}
public void setArquivo ( byte [] arquivo ) {
this . arquivo = arquivo ;
}
@Override
public int hashCode () {
int hash = 0 ;
hash += ( anexoId != null ? anexoId . hashCode () : 0 );
return hash ;
}
@Override
public boolean equals ( Object object ) {
// TODO: Warning - this method won't work in the case the id fields are not set
if ( ! ( object instanceof Anexo )) {
return false ;
}
Anexo other = ( Anexo ) object ;
if (( this . anexoId == null && other . anexoId != null ) || ( this . anexoId != null && ! this . anexoId . equals ( other . anexoId ))) {
return false ;
}
return true ;
}
@Override
public String toString () {
return "negocio.entidade.Anexo[ anexoId=" + anexoId + " ]" ;
}
}
classe ManagedBean
@ ManagedBean ( name = "anexoMB" )
@ SessionScoped
public class AnexoMB implements Serializable {
private Anexo anexo ;
@ EJB
private AnexoFachada anexoFachada ;
public void AnexoMB (){}
public Anexo getAnexo () {
return anexo ;
}
public void setAnexo ( Anexo anexo ) {
this . anexo = anexo ;
}
public String inserir () {
try {
anexoFachada . inserir ( this . getAnexo ());
return "/anexo/ListarUsuario" ;
} catch ( Exception e ) {
return "/anexo/InserirUsuario" ;
}
}
}
ae que vem minha dúvida na classe DAO eu posso fazer dessa forma ?
@Stateless
public class AnexoDAO {
@PersistenceContext
private EntityManager em ;
public void inserir ( Anexo anexo ) {
boolean sucesso = false ;
try {
em . merge ( anexo );
sucesso = true ;
} catch ( Exception e ) {
e . getMessage ();
}
// return sucesso ;
}
}
onde posso colocar meu metodo que será responsavem por pegar minha imagem e colocar num array de byte ?
e_novaski 25 de fev. de 2012
Boa tarde, alexandrergtk
seguinte para gravar um arquivo pdf eu consegui utilizando a seguinte procedure, mas para imagem ainda nao consegui
public byte [] convertePDF ( String arquivo ) throws FileNotFoundException {
File file = new File ( arquivo ) ;
FileInputStream fis = new FileInputStream ( file ) ;
ByteArrayOutputStream bos = new ByteArrayOutputStream () ;
byte [] buf = new byte [1024 ];
try {
for ( int readNum ; (readNum = fis.read(buf)) != -1;) {
bos .write ( buf , 0 , readNum ) ;
}
} catch ( IOException ex ) {
ex .getMessage () ;
}
byte [] bytes = bos .toByteArray () ;
return bytes ;
}
para chamar o metodo
projetoArquivo . setArquivo ( convertePDF ( "C:/documento.pdf" ));
se alguem tiver uma solucao para fazer a mesma coisa com imagem agradeco
e_novaski 25 de fev. de 2012
quando eu tento usar a mesma função colocando uma imagem ele dah o seguinte erro
javax . faces . el . EvaluationException : javax . ejb . EJBException : Transaction aborted
at javax . faces . component . MethodBindingMethodExpressionAdapter . invoke ( MethodBindingMethodExpressionAdapter . java : 102 )
at com . sun . faces . application . ActionListenerImpl . processAction ( ActionListenerImpl . java : 102 )
at javax . faces . component . UICommand . broadcast ( UICommand . java : 315 )
at javax . faces . component . UIViewRoot . broadcastEvents ( UIViewRoot . java : 794 )
at javax . faces . component . UIViewRoot . processApplication ( UIViewRoot . java : 1259 )
at com . sun . faces . lifecycle . InvokeApplicationPhase . execute ( InvokeApplicationPhase . java : 81 )
at com . sun . faces . lifecycle . Phase . doPhase ( Phase . java : 101 )
at com . sun . faces . lifecycle . LifecycleImpl . execute ( LifecycleImpl . java : 118 )
at javax . faces . webapp . FacesServlet . service ( FacesServlet . java : 593 )
at org . apache . catalina . core . StandardWrapper . service ( StandardWrapper . java : 1539 )
at org . apache . catalina . core . StandardWrapperValve . invoke ( StandardWrapperValve . java : 281 )
at org . apache . catalina . core . StandardContextValve . invoke ( StandardContextValve . java : 175 )
at org . apache . catalina . core . StandardPipeline . doInvoke ( StandardPipeline . java : 655 )
at org . apache . catalina . core . StandardPipeline . invoke ( StandardPipeline . java : 595 )
at com . sun . enterprise . web . WebPipeline . invoke ( WebPipeline . java : 98 )
at com . sun . enterprise . web . PESessionLockingStandardPipeline . invoke ( PESessionLockingStandardPipeline . java : 91 )
at org . apache . catalina . core . StandardHostValve . invoke ( StandardHostValve . java : 162 )
at org . apache . catalina . connector . CoyoteAdapter . doService ( CoyoteAdapter . java : 330 )
at org . apache . catalina . connector . CoyoteAdapter . service ( CoyoteAdapter . java : 231 )
at com . sun . enterprise . v3 . services . impl . ContainerMapper . service ( ContainerMapper . java : 174 )
at com . sun . grizzly . http . ProcessorTask . invokeAdapter ( ProcessorTask . java : 828 )
at com . sun . grizzly . http . ProcessorTask . doProcess ( ProcessorTask . java : 725 )
at com . sun . grizzly . http . ProcessorTask . process ( ProcessorTask . java : 1019 )
at com . sun . grizzly . http . DefaultProtocolFilter . execute ( DefaultProtocolFilter . java : 225 )
at com . sun . grizzly . DefaultProtocolChain . executeProtocolFilter ( DefaultProtocolChain . java : 137 )
at com . sun . grizzly . DefaultProtocolChain . execute ( DefaultProtocolChain . java : 104 )
at com . sun . grizzly . DefaultProtocolChain . execute ( DefaultProtocolChain . java : 90 )
at com . sun . grizzly . http . HttpProtocolChain . execute ( HttpProtocolChain . java : 79 )
at com . sun . grizzly . ProtocolChainContextTask . doCall ( ProtocolChainContextTask . java : 54 )
at com . sun . grizzly . SelectionKeyContextTask . call ( SelectionKeyContextTask . java : 59 )
at com . sun . grizzly . ContextTask . run ( ContextTask . java : 71 )
at com . sun . grizzly . util . AbstractThreadPool$Worker . doWork ( AbstractThreadPool . java : 532 )
at com . sun . grizzly . util . AbstractThreadPool$Worker . run ( AbstractThreadPool . java : 513 )
at java . lang . Thread . run ( Thread . java : 722 )
Caused by : javax . ejb . EJBException : Transaction aborted
at com . sun . ejb . containers . BaseContainer . completeNewTx ( BaseContainer . java : 5120 )
at com . sun . ejb . containers . BaseContainer . postInvokeTx ( BaseContainer . java : 4879 )
at com . sun . ejb . containers . BaseContainer . postInvoke ( BaseContainer . java : 2039 )
at com . sun . ejb . containers . BaseContainer . postInvoke ( BaseContainer . java : 1990 )
at com . sun . ejb . containers . EJBLocalObjectInvocationHandler . invoke ( EJBLocalObjectInvocationHandler . java : 222 )
at com . sun . ejb . containers . EJBLocalObjectInvocationHandlerDelegate . invoke ( EJBLocalObjectInvocationHandlerDelegate . java : 88 )
at $Proxy264 . gravarArquivo ( Unknown Source )
at br . com . entecnologia . dao . < strong > EJB31_Generated__ProjetoDAO__Intf____Bean </ strong > . gravarArquivo ( Unknown Source )
at br . com . entecnologia . controle . ProjetoControle . gravarArquivo ( ProjetoControle . java : 49 )
at br . com . entecnologia . controle . org$jboss$weld$bean - web - ManagedBean - class_br$com$entecnologia$controle$ProjetoControle_$$ < em > WeldClientProxy . gravarArquivo ( org$jboss$weld$bean - web - ManagedBean - class_br$com$entecnologia$controle$ProjetoControle </ em > $$_WeldClientProxy . java )
at sun . reflect . NativeMethodAccessorImpl . invoke0 ( Native Method )
at sun . reflect . NativeMethodAccessorImpl . invoke ( NativeMethodAccessorImpl . java : 57 )
at sun . reflect . DelegatingMethodAccessorImpl . invoke ( DelegatingMethodAccessorImpl . java : 43 )
at java . lang . reflect . Method . invoke ( Method . java : 601 )
at com . sun . el . parser . AstValue . invoke ( AstValue . java : 234 )
at com . sun . el . MethodExpressionImpl . invoke ( MethodExpressionImpl . java : 297 )
at org . jboss . weld . util . el . ForwardingMethodExpression . invoke ( ForwardingMethodExpression . java : 43 )
at org . jboss . weld . el . WeldMethodExpression . invoke ( WeldMethodExpression . java : 56 )
at com . sun . faces . facelets . el . TagMethodExpression . invoke ( TagMethodExpression . java : 105 )
at javax . faces . component . MethodBindingMethodExpressionAdapter . invoke ( MethodBindingMethodExpressionAdapter . java : 88 )
… 33 more
Caused by : javax . transaction . RollbackException : Transaction marked for rollback .
at com . sun . enterprise . transaction . JavaEETransactionImpl . commit ( JavaEETransactionImpl . java : 473 )
at com . sun . enterprise . transaction . JavaEETransactionManagerSimplified . commit ( JavaEETransactionManagerSimplified . java : 852 )
at com . sun . ejb . containers . BaseContainer . completeNewTx ( BaseContainer . java : 5114 )
… 52 more
Caused by : Exception [ EclipseLink -4002 ] ( Eclipse Persistence Services - 2.3.0 . v20110604 - r9504 ) : org . eclipse . persistence . exceptions . DatabaseException
Internal Exception : com . mysql . jdbc . PacketTooBigException : Packet for query is too large ( 1555787 > 1048576 ). You can change this value on the server by setting the max_allowed_packet ’ variable .
Error Code : 0
Call : INSERT INTO projeto ( ARQUIVO , TIPO , i_projeto , ORDEM , ANO , i_entidade ) VALUES ( ? , ? , ? , ? , ? , ? )
bind => [ 6 parameters bound ]
Query : InsertObjectQuery ( br . com . entecnologia . modelo . ProjetoArquivo @7e1 )
at org . eclipse . persistence . exceptions . DatabaseException . sqlException ( DatabaseException . java : 324 )
at org . eclipse . persistence . internal . databaseaccess . DatabaseAccessor . executeDirectNoSelect ( DatabaseAccessor . java : 840 )
at org . eclipse . persistence . internal . databaseaccess . DatabaseAccessor . executeNoSelect ( DatabaseAccessor . java : 906 )
at org . eclipse . persistence . internal . databaseaccess . DatabaseAccessor . basicExecuteCall ( DatabaseAccessor . java : 592 )
at org . eclipse . persistence . internal . databaseaccess . DatabaseAccessor . executeCall ( DatabaseAccessor . java : 535 )
at org . eclipse . persistence . internal . sessions . AbstractSession . basicExecuteCall ( AbstractSession . java : 1702 )
at org . eclipse . persistence . sessions . server . ClientSession . executeCall ( ClientSession . java : 253 )
at org . eclipse . persistence . internal . queries . DatasourceCallQueryMechanism . executeCall ( DatasourceCallQueryMechanism . java : 207 )
at org . eclipse . persistence . internal . queries . DatasourceCallQueryMechanism . executeCall ( DatasourceCallQueryMechanism . java : 193 )
at org . eclipse . persistence . internal . queries . DatasourceCallQueryMechanism . insertObject ( DatasourceCallQueryMechanism . java : 342 )
at org . eclipse . persistence . internal . queries . StatementQueryMechanism . insertObject ( StatementQueryMechanism . java : 162 )
at org . eclipse . persistence . internal . queries . StatementQueryMechanism . insertObject ( StatementQueryMechanism . java : 177 )
at org . eclipse . persistence . internal . queries . DatabaseQueryMechanism . insertObjectForWrite ( DatabaseQueryMechanism . java : 472 )
at org . eclipse . persistence . queries . InsertObjectQuery . executeCommit ( InsertObjectQuery . java : 80 )
at org . eclipse . persistence . queries . InsertObjectQuery . executeCommitWithChangeSet ( InsertObjectQuery . java : 90 )
at org . eclipse . persistence . internal . queries . DatabaseQueryMechanism . executeWriteWithChangeSet ( DatabaseQueryMechanism . java : 287 )
at org . eclipse . persistence . queries . WriteObjectQuery . executeDatabaseQuery ( WriteObjectQuery . java : 58 )
at org . eclipse . persistence . queries . DatabaseQuery . execute ( DatabaseQuery . java : 829 )
at org . eclipse . persistence . queries . DatabaseQuery . executeInUnitOfWork ( DatabaseQuery . java : 728 )
at org . eclipse . persistence . queries . ObjectLevelModifyQuery . executeInUnitOfWorkObjectLevelModifyQuery ( ObjectLevelModifyQuery . java : 108 )
at org . eclipse . persistence . queries . ObjectLevelModifyQuery . executeInUnitOfWork ( ObjectLevelModifyQuery . java : 85 )
at org . eclipse . persistence . internal . sessions . UnitOfWorkImpl . internalExecuteQuery ( UnitOfWorkImpl . java : 2863 )
at org . eclipse . persistence . internal . sessions . AbstractSession . executeQuery ( AbstractSession . java : 1501 )
at org . eclipse . persistence . internal . sessions . AbstractSession . executeQuery ( AbstractSession . java : 1483 )
at org . eclipse . persistence . internal . sessions . AbstractSession . executeQuery ( AbstractSession . java : 1443 )
at org . eclipse . persistence . internal . sessions . CommitManager . commitNewObjectsForClassWithChangeSet ( CommitManager . java : 224 )
at org . eclipse . persistence . internal . sessions . CommitManager . commitAllObjectsWithChangeSet ( CommitManager . java : 123 )
at org . eclipse . persistence . internal . sessions . AbstractSession . writeAllObjectsWithChangeSet ( AbstractSession . java : 3784 )
at org . eclipse . persistence . internal . sessions . UnitOfWorkImpl . commitToDatabase ( UnitOfWorkImpl . java : 1407 )
at org . eclipse . persistence . internal . sessions . RepeatableWriteUnitOfWork . commitToDatabase ( RepeatableWriteUnitOfWork . java : 634 )
at org . eclipse . persistence . internal . sessions . UnitOfWorkImpl . commitToDatabaseWithChangeSet ( UnitOfWorkImpl . java : 1497 )
at org . eclipse . persistence . internal . sessions . UnitOfWorkImpl . issueSQLbeforeCompletion ( UnitOfWorkImpl . java : 3135 )
at org . eclipse . persistence . internal . sessions . RepeatableWriteUnitOfWork . issueSQLbeforeCompletion ( RepeatableWriteUnitOfWork . java : 344 )
at org . eclipse . persistence . transaction . AbstractSynchronizationListener . beforeCompletion ( AbstractSynchronizationListener . java : 157 )
at org . eclipse . persistence . transaction . JTASynchronizationListener . beforeCompletion ( JTASynchronizationListener . java : 68 )
at com . sun . enterprise . transaction . JavaEETransactionImpl . commit ( JavaEETransactionImpl . java : 435 )
… 54 more
Caused by : com . mysql . jdbc . PacketTooBigException : Packet for query is too large ( 1555787 > 1048576 ). You can change this value on the server by setting the max_allowed_packet ’ variable .
at com . mysql . jdbc . MysqlIO . send ( MysqlIO . java : 3248 )
at com . mysql . jdbc . MysqlIO . sendCommand ( MysqlIO . java : 1940 )
at com . mysql . jdbc . MysqlIO . sqlQueryDirect ( MysqlIO . java : 2113 )
at com . mysql . jdbc . ConnectionImpl . execSQL ( ConnectionImpl . java : 2568 )
at com . mysql . jdbc . PreparedStatement . executeInternal ( PreparedStatement . java : 2113 )
at com . mysql . jdbc . PreparedStatement . executeUpdate ( PreparedStatement . java : 2409 )
at com . mysql . jdbc . PreparedStatement . executeUpdate ( PreparedStatement . java : 2327 )
at com . mysql . jdbc . PreparedStatement . executeUpdate ( PreparedStatement . java : 2312 )
at org . eclipse . persistence . internal . databaseaccess . DatabaseAccessor . executeDirectNoSelect ( DatabaseAccessor . java : 831 )
… 88 more
e_novaski 26 de fev. de 2012
Bom dia, consegui resolver o problema da seguinte forma:
pagina
<h:form>
<rich:fileUpload fileUploadListener= "#{projetoControle.enviaArquivo}" id= "upload" acceptedTypes= "jpg, gif, png, bmp, pdf, doc, xls, docx, xlsx"
uploadLabel= "Executar upload" addLabel= "Adicionar arquivo" clearAllLabel= "Limpar toda lista"
clearLabel= " " deleteLabel= "Excluir" doneLabel= "Arquivo enviado com sucesso!" />
</h:form>
Controle
public void novoArquivo () {
projetoArquivo = new ProjetoArquivo ();
projetoArquivo . setProjetoArquivoPK ( new ProjetoArquivoPK ( 1 , 1 , 2012 , dao . verificaOrdem ()));
}
public void enviaArquivo ( FileUploadEvent evento ) throws Exception {
String nomeArquivo = "" ;
String extensao = "" ;
novoArquivo ();
UploadedFile item = evento . getUploadedFile ();
StringTokenizer st = new StringTokenizer ( item . getName (), "\\" );
while ( st . hasMoreElements ()) {
nomeArquivo = st . nextToken ();
}
int extDot = nomeArquivo . lastIndexOf ( '.' );
if ( extDot > 0 ) {
extensao = nomeArquivo . substring ( extDot + 1 );
}
projetoArquivo . setNome ( item . getName ());
projetoArquivo . setTipo ( extensao );
projetoArquivo . setArquivo ( item . getData ());
dao . gravarArquivo ( projetoArquivo );
}
dao
public boolean gravarArquivo ( ProjetoArquivo projetoDocumento ) {
boolean sucesso = false ;
try {
emArquivo . merge ( projetoDocumento );
sucesso = true ;
} catch ( Exception e ) {
e . getMessage ();
}
return sucesso ;
}
agradeço ajuda de todos…
valeu.
alexandergtk 26 de fev. de 2012
hehehe…agora que vi seu xhtml você está usando richfaces, com essa faces eu já consegui, no momento estou fazendo com primefaces e ele tem mais coisas pra configurar.
vlw