Olá Galera Guj…
Estou com um problema que acho q sei oq é mas nao consigo resolver…
tenho q fazer um save… mas antes busco no bd pra verificar se o registro exite… ate ai blz…
ele tanto insere como buscar… normal… so que…
se o registro ja existe ele da erro… passa pelo if mas… e tenta salvar do msm jeito…
oq sera q ta acontecendo… ele nunca cai no else…
public static void main(String[] args) throws Exception , ValidationException{
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration.configure();
SessionFactory sf = configuration.buildSessionFactory();
Session session = sf.openSession();
GrupoProduto grupo = new GrupoProduto();
grupo.setIdGrupoProduto(28);
grupo.setNomeGrupoProduto("grupo novo 2" );
Dao<GrupoProduto> dao = new Dao<GrupoProduto>(session, GrupoProduto.class);
Transaction t = session.beginTransaction();
if(dao.findById(grupo.getIdGrupoProduto()) == null) {
dao.save(grupo);
t.commit();
}else{
System.out.println(" \n\n Registro ja existente..");
}
session.close();
sf.close();
}
o erro:
17:26:44,051 INFO Version:15 - Hibernate Annotations 3.3.0.GA
17:26:44,082 INFO Environment:514 - Hibernate 3.2.5
17:26:44,098 INFO Environment:547 - hibernate.properties not found
17:26:44,098 INFO Environment:681 - Bytecode provider name : cglib
17:26:44,113 INFO Environment:598 - using JDK 1.4 java.sql.Timestamp handling
17:26:44,254 INFO Configuration:1426 - configuring from resource: /hibernate.cfg.xml
17:26:44,254 INFO Configuration:1403 - Configuration resource: /hibernate.cfg.xml
17:26:44,691 INFO Configuration:1541 - Configured SessionFactory: null
17:26:44,801 INFO AnnotationBinder:398 - Binding entity from annotated class: br.com.PodiumInformatica.beans.Produto
17:26:44,879 INFO EntityBinder:420 - Bind entity br.com.PodiumInformatica.beans.Produto on table cadprodu
17:26:44,988 INFO AnnotationBinder:398 - Binding entity from annotated class: br.com.PodiumInformatica.beans.Laboratorio
17:26:44,988 INFO EntityBinder:420 - Bind entity br.com.PodiumInformatica.beans.Laboratorio on table cadlabor
17:26:44,988 INFO AnnotationBinder:398 - Binding entity from annotated class: br.com.PodiumInformatica.beans.GrupoProduto
17:26:44,988 INFO EntityBinder:420 - Bind entity br.com.PodiumInformatica.beans.GrupoProduto on table cadgrupo
17:26:45,004 INFO AnnotationConfiguration:350 - Hibernate Validator not found: ignoring
17:26:45,144 INFO C3P0ConnectionProvider:81 - C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/avaliacao
17:26:45,144 INFO C3P0ConnectionProvider:82 - Connection properties: {user=root, password=****}
17:26:45,144 INFO C3P0ConnectionProvider:85 - autocommit mode: false
17:26:45,176 INFO MLog:80 - MLog clients using log4j logging.
17:26:45,457 INFO C3P0Registry:204 - Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
17:26:45,613 INFO AbstractPoolBackedDataSource:462 - Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@325f65a2 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@eb386ca5 [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bqon5a8aokc88514k4r1e|e1899b, idleConnectionTestPeriod -> 100, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 180, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@e571ed59 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1bqon5a8aokc88514k4r1e|1c56c60, jdbcUrl -> jdbc:mysql://localhost/avaliacao, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1bqon5a8aokc88514k4r1e|161dfb5, numHelperThreads -> 3 ]
17:26:45,972 INFO SettingsFactory:89 - RDBMS: MySQL, version: 5.1.49-community
17:26:45,972 INFO SettingsFactory:90 - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.0.7 ( $Date: 2007-03-09 22:13:57 +0100 (Fri, 09 Mar 2007) $, $Revision: 6341 $ )
17:26:46,004 INFO Dialect:152 - Using dialect: org.hibernate.dialect.MySQLDialect
17:26:46,019 INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
17:26:46,019 INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
17:26:46,019 INFO SettingsFactory:143 - Automatic flush during beforeCompletion(): disabled
17:26:46,019 INFO SettingsFactory:147 - Automatic session close at end of transaction: disabled
17:26:46,019 INFO SettingsFactory:154 - JDBC batch size: 15
17:26:46,019 INFO SettingsFactory:157 - JDBC batch updates for versioned data: disabled
17:26:46,019 INFO SettingsFactory:162 - Scrollable result sets: enabled
17:26:46,019 INFO SettingsFactory:170 - JDBC3 getGeneratedKeys(): enabled
17:26:46,019 INFO SettingsFactory:178 - Connection release mode: auto
17:26:46,035 INFO SettingsFactory:202 - Maximum outer join fetch depth: 2
17:26:46,035 INFO SettingsFactory:205 - Default batch fetch size: 1
17:26:46,035 INFO SettingsFactory:209 - Generate SQL with comments: disabled
17:26:46,035 INFO SettingsFactory:213 - Order SQL updates by primary key: disabled
17:26:46,035 INFO SettingsFactory:217 - Order SQL inserts for batching: disabled
17:26:46,035 INFO SettingsFactory:386 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
17:26:46,035 INFO ASTQueryTranslatorFactory:24 - Using ASTQueryTranslatorFactory
17:26:46,035 INFO SettingsFactory:225 - Query language substitutions: {}
17:26:46,035 INFO SettingsFactory:230 - JPA-QL strict compliance: disabled
17:26:46,035 INFO SettingsFactory:235 - Second-level cache: enabled
17:26:46,035 INFO SettingsFactory:239 - Query cache: disabled
17:26:46,035 INFO SettingsFactory:373 - Cache provider: org.hibernate.cache.EhCacheProvider
17:26:46,035 INFO SettingsFactory:254 - Optimize cache for minimal puts: disabled
17:26:46,051 INFO SettingsFactory:263 - Structured second-level cache entries: disabled
17:26:46,051 INFO SettingsFactory:290 - Statistics: disabled
17:26:46,051 INFO SettingsFactory:294 - Deleted entity synthetic identifier rollback: disabled
17:26:46,051 INFO SettingsFactory:309 - Default entity-mode: pojo
17:26:46,051 INFO SettingsFactory:313 - Named query checking : enabled
17:26:46,113 INFO SessionFactoryImpl:161 - building session factory
17:26:46,129 WARN ConfigurationFactory:127 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/livia/Avaliacao/lib/ehcache-1.2.3.jar!/ehcache-failsafe.xml
17:26:46,644 INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
17:26:47,019 INFO Dao:79 - *************** BUSCANDO *************
class br.com.PodiumInformatica.beans.GrupoProduto
ID: 28
17:26:47,035 INFO Dao:66 - *************** SAVE *************
br.com.PodiumInformatica.beans.GrupoProduto@afa68a
17:26:47,066 DEBUG SQL:401 - insert into avaliacao.cadgrupo (nom_grupo, cod_grupo) values (?, ?)
17:26:47,113 WARN JDBCExceptionReporter:77 - SQL Error: 1062, SQLState: 23000
17:26:47,113 ERROR JDBCExceptionReporter:78 - Duplicate entry '28' for key 'PRIMARY'
17:26:47,129 ERROR AbstractFlushingEventListener:301 - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at br.com.PodiumInformatica.test.TesteInsereGrupo.main(TesteInsereGrupo.java:34)
Caused by: java.sql.BatchUpdateException: Duplicate entry '28' for key 'PRIMARY'
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1257)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:943)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
... 8 more
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at br.com.PodiumInformatica.test.TesteInsereGrupo.main(TesteInsereGrupo.java:34)
Caused by: java.sql.BatchUpdateException: Duplicate entry '28' for key 'PRIMARY'
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1257)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:943)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
... 8 more
desde ja agradeço…
att…
