[java] org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I'm trying to set up a small working sample of Hibernate that I found here However when I run the code I get the follwing error

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.sample.Person]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at .....


Caused by: org.postgresql.util.PSQLException: ERROR: relation "person" does not exist
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 23 more

But I already have a table by the name person in the database and here's my modified hibernate.cfg.xml

    <!-- hibernate dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>


    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost/testDB</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.show.sql" ></property> 
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    <!-- Automatic schema creation (begin) === -->
    <property name="hibernate.hbm2ddl.auto">create</property>


    <!-- Simple memory-only cache -->
    <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- ############################################ -->
    <!-- # mapping files with external dependencies # -->
    <!-- ############################################ -->

    <mapping resource="com/sample/Person.hbm.xml" />

</session-factory>

It would be great if anyone could point out what Im doing wrong, as this is my first attempt at Hibernate. Thanks!

EDIT: Person.hbm.xml

<class name="com.sample.Person" table="person">

    <id name="id" column="ID">
        <generator class="native" />
    </id>

    <property name="name">
        <column name="NAME" length="16" not-null="true" />
    </property>

    <property name="surname">
        <column name="SURNAME" length="16" not-null="true" />
    </property>

    <property name="address">
        <column name="ADDRESS" length="16" not-null="true" />
    </property>

</class>

EDIT-II: Content of the log file (Postgresql.log)

 2012-02-13 09:23:25 IST LOG:  database system was shut down at 2012-02-10 18:14:57 IST
 2012-02-13 09:23:25 IST FATAL:  the database system is starting up
 2012-02-13 09:23:33 IST LOG:  database system is ready to accept connections
 2012-02-13 09:23:38 IST LOG:  autovacuum launcher started
 2012-02-13 09:46:01 IST ERROR:  syntax error at or near "auto_increment" at character 41
    2012-02-13 09:46:01 IST STATEMENT:  create table person (ID bigint not null         auto_increment, NAME varchar(16) not null, SURNAME varchar(16) not null, ADDRESS varchar(16) not null, primary key (ID)) type=InnoDB
 2012-02-13 09:46:01 IST ERROR:  relation "person" does not exist at character 13
2012-02-13 09:46:01 IST STATEMENT:  insert into person (NAME, SURNAME, ADDRESS) values   ($1, $2, $3) RETURNING *
2012-02-13 09:46:01 IST LOG:  could not receive data from client: No connection could be made because the target machine actively refused it.


2012-02-13 09:46:01 IST LOG:  unexpected EOF on client connection
2012-02-13 09:48:15 IST ERROR:  syntax error at or near "auto_increment" at character 41
2012-02-13 09:48:15 IST STATEMENT:  create table person (ID bigint not null auto_increment, NAME varchar(16) not null, SURNAME varchar(16) not null, ADDRESS varchar(16) not null, primary key (ID)) type=InnoDB
2012-02-13 09:48:15 IST ERROR:  relation "person" does not exist at character 13
2012-02-13 09:48:15 IST STATEMENT:  insert into person (NAME, SURNAME, ADDRESS) values ($1, $2, $3) RETURNING *
 2012-02-13 09:48:15 IST LOG:  could not receive data from client: No connection could be made because the target machine actively refused it.


2012-02-13 09:48:15 IST LOG:  unexpected EOF on client connection

UPDATE: I just noticed something weird, I create the relation in the DB and then run this piece of code, only to see that the table gets deleted as in it just dissapears when I run this code; any idea why this happens?

This question is related to java hibernate orm hibernate-mapping

The answer is


Note:

  1. Its not necessary to specify table name in Person.hbm.xml (........) when you are creating table with same as class name. Also applicable to fields.

  2. While creating "person" table in your respective database,make sure that whatever FILEDS names you specified in Person.hbm.xml must match with table COLUMNS names ELSE you wil get above error.


What do we mean by org.hibernate.exception.SQLGrammarException?

Implementation of JDBCException indicating that the SQL sent to the database server was invalid (syntax error, invalid object references, etc).

and in my words there is a kind of Grammar mistake inside of your hibernate.cfg.xml configuration file,

it happens when you write wrong schema defination property name inside, like below example:

<property name="hibernate.connection.hbm2ddl.auto">create</property>

which supposed to be like:

<property name="hibernate.hbm2ddl.auto">create</property>

I sovled this errors by modifying the Database charset.Old Database charset is cp1252 and i conver to utf-8


I solved the error by modifying the following property in hibernate.cfg.xml

<property name="hibernate.hbm2ddl.auto">validate</property>

Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.

As far as I know you can also change from validate to update e.g.:

<property name="hibernate.hbm2ddl.auto">update</property>

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.


According to the exception, Hibernate wants to write to the table "person", yet in your hbm.xml you define that there is a table "Person", are you sure the correct table exists in your database-schema?


It seems you are connecting to the wrong database. R u sure "jdbc:postgresql://localhost/testDB" will connect you to the actual datasource ?

Generally they are of the form "jdbc://hostname/databasename". Look into Postgresql log file.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to hibernate

Hibernate Error executing DDL via JDBC Statement How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory Disable all Database related auto configuration in Spring Boot Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] HikariCP - connection is not available Hibernate-sequence doesn't exist How to find distinct rows with field in list using JPA and Spring? Spring Data JPA and Exists query

Examples related to orm

How to select specific columns in laravel eloquent Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] How to query between two dates using Laravel and Eloquent? Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? How to Make Laravel Eloquent "IN" Query? How to auto generate migrations with Sequelize CLI from Sequelize models? How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session Select the first 10 rows - Laravel Eloquent How to make join queries using Sequelize on Node.js What is Persistence Context?

Examples related to hibernate-mapping

How can I mark a foreign key constraint using Hibernate annotations? Hibernate table not mapped error in HQL query org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person] Can someone explain mappedBy in JPA and Hibernate? Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance In which case do you use the JPA @JoinTable annotation? How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK? How to map calculated properties with JPA and Hibernate