Problema hibernate e sql server

3 respostas
leandrognaf

Estou tentando inserir um simples arquivo no banco sql server mas n to conseguindo

segue o codigo abaixo.

import modelo.Usuario;

import org.hibernate.Session;

import util.HibernateUtil;
public class TestaInsere {
    

    public static void main (String [] args){
        Usuario user = new Usuario();
        Session session = new HibernateUtil().getSessionFactory().getCurrentSession();
        session.beginTransaction();
        user.setNome("Tiririca");
        user.setEmail("[email removido]");
        session.save(user);
        session.beginTransaction().commit();
    }
}

o erro e o seguinte

02/05/2011 08:35:16 org.hibernate.cfg.annotations.Version <clinit> INFO: Hibernate Annotations 3.3.1.GA 02/05/2011 08:35:16 org.hibernate.cfg.Environment <clinit> INFO: Hibernate 3.2.5 02/05/2011 08:35:17 org.hibernate.cfg.Environment <clinit> INFO: hibernate.properties not found 02/05/2011 08:35:17 org.hibernate.cfg.Environment buildBytecodeProvider INFO: Bytecode provider name : cglib 02/05/2011 08:35:17 org.hibernate.cfg.Environment <clinit> INFO: using JDK 1.4 java.sql.Timestamp handling 02/05/2011 08:35:17 org.hibernate.cfg.Configuration configure INFO: configuring from resource: /hibernate.cfg.xml 02/05/2011 08:35:17 org.hibernate.cfg.Configuration getConfigurationInputStream INFO: Configuration resource: /hibernate.cfg.xml 02/05/2011 08:35:17 org.hibernate.cfg.Configuration addResource INFO: Reading mappings from resource : modelo/Usuario.hbm.xml 02/05/2011 08:35:17 org.hibernate.cfg.Configuration doConfigure INFO: Configured SessionFactory: null 02/05/2011 08:35:17 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues INFO: Mapping class: modelo.Usuario -> Usuario 02/05/2011 08:35:17 org.hibernate.cfg.AnnotationConfiguration secondPassCompile INFO: Hibernate Validator not found: ignoring 02/05/2011 08:35:17 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Using Hibernate built-in connection pool (not for production use!) 02/05/2011 08:35:17 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Hibernate connection pool size: 20 02/05/2011 08:35:17 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: autocommit mode: false 02/05/2011 08:35:18 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: using driver: com.microsoft.sqlserver.jdbc.SQLServerDriver at URL: jdbc:sqlserver://localhost:1433;databaseName=agenda 02/05/2011 08:35:18 org.hibernate.connection.DriverManagerConnectionProvider configure INFO: connection properties: {user=sa, password=****} 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: RDBMS: Microsoft SQL Server, version: 9.00.1399 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC driver: Microsoft SQL Server JDBC Driver 2.0, version: 2.0.1803.100 02/05/2011 08:35:19 org.hibernate.dialect.Dialect <init> INFO: Using dialect: org.hibernate.dialect.SQLServerDialect 02/05/2011 08:35:19 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory INFO: Using default transaction strategy (direct JDBC transactions) 02/05/2011 08:35:19 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Automatic flush during beforeCompletion(): disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Automatic session close at end of transaction: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Scrollable result sets: enabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: JDBC3 getGeneratedKeys(): enabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Connection release mode: auto 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Default batch fetch size: 1 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Generate SQL with comments: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Order SQL updates by primary key: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Order SQL inserts for batching: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 02/05/2011 08:35:19 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init> INFO: Using ASTQueryTranslatorFactory 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Query language substitutions: {} 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: JPA-QL strict compliance: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Second-level cache: enabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Query cache: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory createCacheProvider INFO: Cache provider: org.hibernate.cache.NoCacheProvider 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Optimize cache for minimal puts: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Structured second-level cache entries: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Statistics: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Deleted entity synthetic identifier rollback: disabled 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Default entity-mode: pojo 02/05/2011 08:35:19 org.hibernate.cfg.SettingsFactory buildSettings INFO: Named query checking : enabled 02/05/2011 08:35:19 org.hibernate.impl.SessionFactoryImpl <init> INFO: building session factory 02/05/2011 08:35:20 org.hibernate.impl.SessionFactoryObjectFactory addInstance INFO: Not binding factory to JNDI, no JNDI name configured 02/05/2011 08:35:20 org.hibernate.util.JDBCExceptionReporter logExceptions AVISO: SQL Error: 544, SQLState: S0001 02/05/2011 08:35:20 org.hibernate.util.JDBCExceptionReporter logExceptions GRAVE: Não é possível inserir um valor explícito para a coluna de identidade na tabela 'Usuario' quando IDENTITY_INSERT está definido como OFF. 02/05/2011 08:35:20 org.hibernate.event.def.AbstractFlushingEventListener performExecutions GRAVE: Could not synchronize database state with session org.hibernate.exception.SQLGrammarException: could not insert: [modelo.Usuario] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2267) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2660) at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:56) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234) 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 TestaInsere.main(TestaInsere.java:17) Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Não é possível inserir um valor explícito para a coluna de identidade na tabela 'Usuario' quando IDENTITY_INSERT está definido como OFF. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:388) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:338) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:185) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:160) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:306) at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2247) ... 11 more Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [modelo.Usuario] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2267) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2660) at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:56) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234) 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 TestaInsere.main(TestaInsere.java:17) Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Não é possível inserir um valor explícito para a coluna de identidade na tabela 'Usuario' quando IDENTITY_INSERT está definido como OFF. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:388) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:338) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:185) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:160) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:306) at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2247) ... 11 more Java Result: 1 CONSTRUÍDO COM SUCESSO (tempo total: 4 segundos)

se alguem puder me da uma luz agradeço :slight_smile:

3 Respostas

Scoobydoo

Provavelmente tais com problema de Primary Key…

Você definiu o campo PK da sua tabela como Auto-incremento?
Você implementou um gerador padrão ?

leandrognaf

Esse aqui e o script da minha tabela

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_Usuario
	(
	id numeric(18, 0) NOT NULL IDENTITY (1, 1),
	nome varchar(50) NULL,
	email varchar(50) NULL,
	telefone varchar(50) NULL,
	dataNascimento datetime NULL
	)  ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_Usuario ON
GO
IF EXISTS(SELECT * FROM dbo.Usuario)
	 EXEC('INSERT INTO dbo.Tmp_Usuario (id, nome, email, telefone, dataNascimento)
		SELECT id, nome, email, telefone, dataNascimento FROM dbo.Usuario WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_Usuario OFF
GO
DROP TABLE dbo.Usuario
GO
EXECUTE sp_rename N'dbo.Tmp_Usuario', N'Usuario', 'OBJECT' 
GO
ALTER TABLE dbo.Usuario ADD CONSTRAINT
	PK_Usuario_1 PRIMARY KEY CLUSTERED 
	(
	id
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
COMMIT
J

Posta a tua entidade aqui, para a gente ver as anotações que ela tem

Criado 2 de maio de 2011
Ultima resposta 2 de mai. de 2011
Respostas 3
Participantes 3