vcmkrtchyan
vcmkrtchyan

Reputation: 2626

Hibernate table not found

Here is my entity

@Entity
public class User {

    @Id
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And here is my hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>

        <!-- Assume test is the database name -->
        <property name="hibernate.connection.url">
            jdbc:mysql://localhost:3306/test
        </property>
        <property name="hibernate.connection.username">
            root
        </property>
        <property name="hibernate.connection.password">
            root
        </property>

        <!-- List of XML mapping files -->
        <mapping class="User"/>

    </session-factory>
</hibernate-configuration>

I have an empty database called test having user and password "root". But when I try to create a User and save it to database, I get an exception saying

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.user' doesn't exist

What have I done wrong?

Upvotes: 2

Views: 2560

Answers (2)

Masarrat Siddiqui
Masarrat Siddiqui

Reputation: 27

Add below property in your configuration file.

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

Thanks

Upvotes: 0

K139
K139

Reputation: 3669

It's because the test.user is not available in database.

Either you need to create the table before starting your application sever

(or)

Enable the hibernate DDL generation to true, to let the hibernate create the table if it does not exist. (Don't do it in production or QA environment, as it is not a good practice).

Add this to the hibernate properties list.

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

Upvotes: 3

Related Questions