flaviochess 25 de set. de 2012
b10machado, coloca o seu persistence.xml no diretório SRC/conf/
b10machado 25 de set. de 2012
b10machado 25 de set. de 2012
ta com esse erro agora!!
public static void main ( String [] args ) {
EntityManagerFactory emf = Persistence . createEntityManagerFactory ( "nomeDaPersistenceUnit" );
EntityManager em = emf . createEntityManager ();
try {
em . getTransaction (). begin ();
User user = new User ();
user . setNome ( "abc123" );
user . setSobrenome ( "bill" );
[ b ] em . persist ( user ); [/ b ] //nessa linha da pau!!
em . getTransaction (). commit ();
}
catch ( Exception e ) {
em . getTransaction (). rollback ();
e . printStackTrace ();
}
finally {
emf . close ();
}
System . out . println ( "It is over" );
}
Hibernate : insert into USUARIO1 ( id , nome , sobrenome ) values ( default , ?, ?)
at org . hibernate . exception . SQLStateConverter . handledNonSpecificException ( SQLStateConverter . java : 103 )
at org . hibernate . exception . SQLStateConverter . convert ( SQLStateConverter . java : 91 )
at org . hibernate . exception . JDBCExceptionHelper . convert ( JDBCExceptionHelper . java : 43 )
at org . hibernate . exception . JDBCExceptionHelper . convert ( JDBCExceptionHelper . java : 29 )
at org . hibernate . tool . hbm2ddl . DatabaseMetadata . getTableMetadata ( DatabaseMetadata . java : 105 )
at org . hibernate . cfg . Configuration . generateSchemaUpdateScript ( Configuration . java : 948 )
at org . hibernate . tool . hbm2ddl . SchemaUpdate . execute ( SchemaUpdate . java : 140 )
at org . hibernate . impl . SessionFactoryImpl .( SessionFactoryImpl . java : 314 )
at org . hibernate . cfg . Configuration . buildSessionFactory ( Configuration . java : 1294 )
at org . hibernate . cfg . AnnotationConfiguration . buildSessionFactory ( AnnotationConfiguration . java : 859 )
at org . hibernate . ejb . Ejb3Configuration . buildEntityManagerFactory ( Ejb3Configuration . java : 669 )
at org . hibernate . ejb . HibernatePersistence . createEntityManagerFactory ( HibernatePersistence . java : 126 )
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 51 )
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 33 )
at com . Main . main ( Main . java : 13 )
Caused by : java . sql . SQLException : Lançada a exceção ‘ java . sql . SQLException : Não foi possível obter o bloqueio dentro do tempo requerido . ’ ao avaliar a expressão .
at org . apache . derby . client . am . SQLExceptionFactory40 . getSQLException ( Unknown Source )
at org . apache . derby . client . am . SqlException . getSQLException ( Unknown Source )
at org . apache . derby . client . am . DatabaseMetaData . getTables ( Unknown Source )
at org . hibernate . tool . hbm2ddl . DatabaseMetadata . getTableMetadata ( DatabaseMetadata . java : 67 )
… 10 more
Caused by : org . apache . derby . client . am . SqlException : Lançada a exceção ‘ java . sql . SQLException : Não foi possível obter o bloqueio dentro do tempo requerido . ’ ao avaliar a expressão .
at org . apache . derby . client . am . Statement . completeExecute ( Unknown Source )
at org . apache . derby . client . net . NetStatementReply . parseEXCSQLSTTreply ( Unknown Source )
at org . apache . derby . client . net . NetStatementReply . readExecuteCall ( Unknown Source )
at org . apache . derby . client . net . StatementReply . readExecuteCall ( Unknown Source )
at org . apache . derby . client . net . NetStatement . readExecuteCall_ ( Unknown Source )
at org . apache . derby . client . am . Statement . readExecuteCall ( Unknown Source )
at org . apache . derby . client . am . PreparedStatement . flowExecute ( Unknown Source )
at org . apache . derby . client . am . PreparedStatement . executeQueryX ( Unknown Source )
at org . apache . derby . client . am . DatabaseMetaData . executeCatalogQuery ( Unknown Source )
at org . apache . derby . client . am . DatabaseMetaData . getTablesX ( Unknown Source )
… 12 more
Caused by : org . apache . derby . client . am . SqlException : Não foi possível obter o bloqueio dentro do tempo requerido .
… 22 more
b10machado 25 de set. de 2012
no printStackTrace();
so aparece isso :s
Hibernate: insert into USUARIO1 (id, nome, sobrenome) values (default, ?, ?)
flaviochess 25 de set. de 2012
Aí no seu main você rodou com essa linha assim mesmo:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("nomeDaPersistenceUnit");
??
b10machado 25 de set. de 2012
sim por causa do meu persistence
<?xml version="1.0" encoding="UTF-8"?>
<persistence version= "1.0" xmlns= "http://java.sun.com/xml/ns/persistence" >
<persistence-unit name= "nomeDaPersistenceUnit" >
<provider> org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name= "hibernate.show_sql" value= "true" />
<property name= "hibernate.dialect" value= "org.hibernate.dialect.DerbyDialect" />
<property name= "hibernate.connection.driver_class" value= "org.apache.derby.jdbc.ClientDriver" />
<property name= "hibernate.connection.url" value= "jdbc:derby://localhost:1527/Teste" />
<property name= "hibernate.connection.username" value= "administrador" />
<property name= "hibernate.connection.password" value= "admin" />
<property name= "hibernate.hbm2ddl.auto" value= "update" />
</properties>
</persistence-unit>
</persistence>
b10machado 25 de set. de 2012
meio doido, a tabela sem nenhum dado da pau tando com o set id na mao ou por anotation, inserir o 1 registro na mao no banco, e ai teste o programa com o set id na mao no indice 2 inseriu normal, voltei ao anotation e deu pau… to mais perdido q cego em tiroteio…
<?xml version="1.0" encoding="UTF-8"?>
<persistence version= "1.0" xmlns= "http://java.sun.com/xml/ns/persistence" >
<persistence-unit name= "nomeDaPersistenceUnit" >
<provider> org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name= "hibernate.show_sql" value= "true" />
<property name= "hibernate.dialect" value= "org.hibernate.dialect.DerbyDialect" />
<property name= "hibernate.connection.driver_class" value= "org.apache.derby.jdbc.ClientDriver" />
<property name= "hibernate.connection.url" value= "jdbc:derby://localhost:1527/Teste" />
<property name= "hibernate.connection.username" value= "administrador" />
<property name= "hibernate.connection.password" value= "admin" />
<property name= "hibernate.hbm2ddl.auto" value= "update" />
</properties>
</persistence-unit>
</persistence>
package com ;
import javax.persistence.Column ;
import javax.persistence.Entity ;
import javax.persistence.GeneratedValue ;
import javax.persistence.GenerationType ;
import javax.persistence.Id ;
import javax.persistence.Table ;
@Entity
@Table ( name = "USUARIO1" )
public class User {
@Id
//@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column ( name = "id" )
private int id ;
@Column ( name = "nome" )
private String nome ;
@Column ( name = "sobrenome" )
private String sobrenome ;
@Override
public boolean equals ( Object obj ) {
if ( obj instanceof User ){
User user = ( User ) obj ;
return user . getId () == this . getId ();
}
return false ;
}
public int getId () {
return id ;
}
public void setId ( int id ) {
this . id = id ;
}
public String getNome () {
return nome ;
}
public void setNome ( String nome ) {
this . nome = nome ;
}
public String getSobrenome () {
return sobrenome ;
}
public void setSobrenome ( String sobrenome ) {
this . sobrenome = sobrenome ;
}
}
package com ;
import javax.persistence.EntityManager ;
import javax.persistence.EntityManagerFactory ;
import javax.persistence.Persistence ;
public class Main {
/**
* @param args
*/
public static void main ( String [] args ) {
EntityManagerFactory emf = Persistence . createEntityManagerFactory ( "nomeDaPersistenceUnit" );
EntityManager em = emf . createEntityManager ();
try {
em . getTransaction (). begin ();
User user = new User ();
user . setId ( 2 );
user . setNome ( "Rafsrl" );
user . setSobrenome ( "doido" );
em . persist ( user );
em . getTransaction (). commit ();
}
catch ( Exception e ) {
em . getTransaction (). rollback ();
e . printStackTrace ();
}
finally {
emf . close ();
}
System . out . println ( "It is over" );
}}
javax . persistence . EntityExistsException : org . hibernate . exception . ConstraintViolationException : could not insert : [ com . User ]
at org . hibernate . ejb . AbstractEntityManagerImpl . throwPersistenceException ( AbstractEntityManagerImpl . java : 612 )
at org . hibernate . ejb . AbstractEntityManagerImpl . persist ( AbstractEntityManagerImpl . java : 226 )
at com . Main . main ( Main . java : 25 )
Caused by : org . hibernate . exception . ConstraintViolationException : could not insert : [ com . User ]
at org . hibernate . exception . SQLStateConverter . convert ( SQLStateConverter . java : 71 )
at org . hibernate . exception . JDBCExceptionHelper . convert ( JDBCExceptionHelper . java : 43 )
at org . hibernate . id . insert . AbstractSelectingDelegate . performInsert ( AbstractSelectingDelegate . java : 40 )
at org . hibernate . persister . entity . AbstractEntityPersister . insert ( AbstractEntityPersister . java : 2158 )
at org . hibernate . persister . entity . AbstractEntityPersister . insert ( AbstractEntityPersister . java : 2638 )
at org . hibernate . action . EntityIdentityInsertAction . execute ( EntityIdentityInsertAction . java : 48 )
at org . hibernate . engine . ActionQueue . execute ( ActionQueue . java : 250 )
at org . hibernate . event . def . AbstractSaveEventListener . performSaveOrReplicate ( AbstractSaveEventListener . java : 298 )
at org . hibernate . event . def . AbstractSaveEventListener . performSave ( AbstractSaveEventListener . java : 181 )
at org . hibernate . event . def . AbstractSaveEventListener . saveWithGeneratedId ( AbstractSaveEventListener . java : 107 )
at org . hibernate . ejb . event . EJB3PersistEventListener . saveWithGeneratedId ( EJB3PersistEventListener . java : 49 )
at org . hibernate . event . def . DefaultPersistEventListener . entityIsTransient ( DefaultPersistEventListener . java : 131 )
at org . hibernate . event . def . DefaultPersistEventListener . onPersist ( DefaultPersistEventListener . java : 87 )
at org . hibernate . event . def . DefaultPersistEventListener . onPersist ( DefaultPersistEventListener . java : 38 )
at org . hibernate . impl . SessionImpl . firePersist ( SessionImpl . java : 618 )
at org . hibernate . impl . SessionImpl . persist ( SessionImpl . java : 592 )
at org . hibernate . impl . SessionImpl . persist ( SessionImpl . java : 596 )
at org . hibernate . ejb . AbstractEntityManagerImpl . persist ( AbstractEntityManagerImpl . java : 220 )
… 1 more
Caused by : java . sql . SQLIntegrityConstraintViolationException : A coluna ‘ ID ’ não aceita valor nulo .
at org . apache . derby . client . am . SQLExceptionFactory40 . getSQLException ( Unknown Source )
at org . apache . derby . client . am . SqlException . getSQLException ( Unknown Source )
at org . apache . derby . client . am . PreparedStatement . executeUpdate ( Unknown Source )
at org . hibernate . id . insert . AbstractSelectingDelegate . performInsert ( AbstractSelectingDelegate . java : 33 )
… 16 more
Caused by : org . apache . derby . client . am . SqlException : A coluna ‘ ID ’ não aceita valor nulo .
at org . apache . derby . client . am . Statement . completeExecute ( Unknown Source )
at org . apache . derby . client . net . NetStatementReply . parseEXCSQLSTTreply ( Unknown Source )
at org . apache . derby . client . net . NetStatementReply . readExecute ( Unknown Source )
at org . apache . derby . client . net . StatementReply . readExecute ( Unknown Source )
at org . apache . derby . client . net . NetPreparedStatement . readExecute_ ( Unknown Source )
at org . apache . derby . client . am . PreparedStatement . readExecute ( Unknown Source )
at org . apache . derby . client . am . PreparedStatement . flowExecute ( Unknown Source )
at org . apache . derby . client . am . PreparedStatement . executeUpdateX ( Unknown Source )
… 18 more
b10machado 25 de set. de 2012
pessoal achei onde esta o problema mais na a soluçao
@Id
@GeneratedValue ( strategy = GenerationType . AUTO )
private int id ;
nao esta gerando o id corretamente, alguem sabe como funciona essa parte para gerar automaticamente…
rof20004 25 de set. de 2012
@Id
@SequenceGenerator (name = “NOMEDATABELA_GENERATION”, sequenceName = “nome_da_tabela_id_seq”, allocationSize = 1)
@GeneratedValue (strategy = GenerationType.SEQUENCE, generator = “NOMEDATABELA_GENERATION”)
@Column (name = “id”)
poe isso ae no id (primary key), e tem que configurar no banco ele como sequence.
b10machado 26 de set. de 2012
cara essa é minha tabela, me da uma ajuda que eu nao consegui
tb_usuario
smallint id autoincrement start 1 increment 1
varchar nome
varchar sobrenome
@Id (aki blz)
@SequenceGenerator (name = “tb_usuario_GENERATION”, sequenceName = “nome_da_tabela_id_seq” (nao entendi aqui), allocationSize = 1)
@GeneratedValue (strategy = GenerationType.SEQUENCE, generator = “tb_usuario_GENERATION”)
@Column (name = “id”)
rof20004 26 de set. de 2012
Muda no strategy de .SEQUENCE para .AUTO
@GeneratedValue (strategy = GenerationType.AUTO , generator = “tb_usuario_GENERATION”)
e pode tirar o sequenceName la do SequenceGenerator, na verdade, pode tirar o @SequenceGenerator todinho, porque aquilo ali eu uso no oracle. Não sei qual Database você está usando.
rof20004 26 de set. de 2012
Tira o generator também, deixa assim e faz um teste.
@Id
@GeneratedValue ( strategy = GenerationType . AUTO )
private Integer id ;
b10machado 26 de set. de 2012
@Id
@GeneratedValue ( strategy = GenerationType . AUTO , generator = "USUARIO12_GENERATION" )
@Column ( name = "id" )
private int id ;
deu certo nao :S, to usando o banco derby do netbeans
javax . faces . event . AbortProcessingException : javax . persistence . PersistenceException : [ PersistenceUnit : nomeDaPersistenceUnit ] Unable to configure EntityManagerFactory
at javax . faces . event . MethodExpressionActionListener . processAction ( MethodExpressionActionListener . java : 182 )
at javax . faces . event . ActionEvent . processListener ( ActionEvent . java : 88 )
at javax . faces . component . UIComponentBase . broadcast ( UIComponentBase . java : 769 )
at javax . faces . component . UICommand . broadcast ( UICommand . java : 300 )
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 : 409 )
at org . apache . catalina . core . ApplicationFilterChain . internalDoFilter ( ApplicationFilterChain . java : 305 )
at org . apache . catalina . core . ApplicationFilterChain . doFilter ( ApplicationFilterChain . java : 210 )
at org . netbeans . modules . web . monitor . server . MonitorFilter . doFilter ( MonitorFilter . java : 393 )
at org . apache . catalina . core . ApplicationFilterChain . internalDoFilter ( ApplicationFilterChain . java : 243 )
at org . apache . catalina . core . ApplicationFilterChain . doFilter ( ApplicationFilterChain . java : 210 )
at org . apache . catalina . core . StandardWrapperValve . invoke ( StandardWrapperValve . java : 225 )
at org . apache . catalina . core . StandardContextValve . invoke ( StandardContextValve . java : 169 )
at org . apache . catalina . authenticator . AuthenticatorBase . invoke ( AuthenticatorBase . java : 472 )
at org . apache . catalina . core . StandardHostValve . invoke ( StandardHostValve . java : 168 )
at org . apache . catalina . valves . ErrorReportValve . invoke ( ErrorReportValve . java : 98 )
at org . apache . catalina . valves . AccessLogValve . invoke ( AccessLogValve . java : 927 )
at org . apache . catalina . core . StandardEngineValve . invoke ( StandardEngineValve . java : 118 )
at org . apache . catalina . connector . CoyoteAdapter . service ( CoyoteAdapter . java : 407 )
at org . apache . coyote . http11 . AbstractHttp11Processor . process ( AbstractHttp11Processor . java : 999 )
at org . apache . coyote . AbstractProtocol $ AbstractConnectionHandler . process ( AbstractProtocol . java : 565 )
at org . apache . tomcat . util . net . JIoEndpoint $ SocketProcessor . run ( JIoEndpoint . java : 307 )
at java . util . concurrent . ThreadPoolExecutor . runWorker ( ThreadPoolExecutor . java : 1110 )
at java . util . concurrent . ThreadPoolExecutor $ Worker . run ( ThreadPoolExecutor . java : 603 )
at java . lang . Thread . run ( Thread . java : 722 )
Caused by : javax . persistence . PersistenceException : [ PersistenceUnit : nomeDaPersistenceUnit ] Unable to configure EntityManagerFactory
at org . hibernate . ejb . Ejb3Configuration . configure ( Ejb3Configuration . java : 265 )
at org . hibernate . ejb . HibernatePersistence . createEntityManagerFactory ( HibernatePersistence . java : 125 )
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 51 )
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 33 )
at com . User . gravar ( User . java : 69 )
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 org . apache . el . parser . AstValue . invoke ( AstValue . java : 264 )
at org . apache . el . MethodExpressionImpl . invoke ( MethodExpressionImpl . java : 278 )
at javax . faces . event . MethodExpressionActionListener . processAction ( MethodExpressionActionListener . java : 153 )
… 28 more
Caused
b10machado 26 de set. de 2012
rof20004 26 de set. de 2012
Xiiiii, de derby sei nada…vou ter que apelar pro google…hehehe…se eu achar algo posto aqui xD fica triste nao, vai dar tudo certo ´-´
rof20004 26 de set. de 2012
Coloca so assim entao:
@Id
@GeneratedValue
private Integer id;
ve se funfa ‘-’
rof20004 26 de set. de 2012
Tem certeza que o problema é na anotacao ?
Dei uma revisada nas exceptions que voce postou, e percebi isso:
Caused by: java.sql.SQLIntegrityConstraintViolationException: A coluna ‘ID’ não aceita valor nulo.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:33)
… 16 more
Nao pode inserir valor null.
e em outras exceptions erro de EntityManager…
Tem certeza que são as anotações ?
b10machado 26 de set. de 2012
sim pq se eu der set no id na mao nao da pau :S ontem eu fiz d alguma forma pelo gerar numero so q era tipo 23458 , 34900 e etc
AmauriSpPoa 28 de set. de 2012
Boa tarde, como está usando o derby, recomendo deixar assim
@GeneratedValue ( strategy = GenerationType . AUTO )
E Retirar o
caso tenha
Exclua a tabela do derby e configure o persistence.xml com essa propriedade
<property name="hibernate.hbm2ddl.auto" value="update"/>
Para ele criar a tabela e criar uma forma automática de gerar os valores da pk(uma sequence interna dele).
Espero ter ajudado.
b10machado 28 de set. de 2012
opaaa ajudou sim deu certinho nem sabia desse esquema de criar pelo xml vlw
b10machado 1 de out. de 2012
entao cara so um problema vi agora…
o id começa com um numero monstro rsrs 524288 …
num tem como ser 1,2,3 e por ai vai ???
AmauriSpPoa 1 de out. de 2012
Cara isso ai já é uma questão do Derby, não sou expert no Derby.
E eu acho que caberia um outro tópico, pois a questão do Hibernate + Jpa já foi, e se tem alguém aqui manja de Derby pode te ajudar. Fica mais fácil se o problema estiver no titulo do tópico.
b10machado 1 de out. de 2012
ata blz e que aki nao dar pra testar em outro banco, vou ver em casa vlw