Search code examples
javahibernatejpajpa-2.0hibernate-mapping

Why hibernate doesn't create tables automatically even with hibernate.hbm2ddl.auto" value="create"?


I'm trying to force hibernate to create a student table if it doesn't exist, but without success, Hibernate library should be able to do that, but I'm getting an error saying there is no such table in the database, not sure what is the problem :

Details:

Student class

import javax.persistence.Entity;
import javax.persistence.Id;


@Entity
public class Student {
    @Id
    int id;

    int phoneNumber;

    public Student() {
    }

    public Student(int id, int phoneNumber) {
        this.id = id;
        this.phoneNumber = phoneNumber;
    }

    public int getId() {
        return id;
    }

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

    public int getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(int phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

Main class

public class Main {
    public static void main(String[] args) {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ss");
        EntityManager entityManager = entityManagerFactory.createEntityManager();


        Student student = new Student(5,55);


        entityManager.getTransaction().begin();
        entityManager.persist(student);
        entityManager.getTransaction().commit();
    }
}

Persistance.xml file

   <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="ss" transaction-type="RESOURCE_LOCAL">

        <class>com.youssef.Student</class>

        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/sotamag" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="" />
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            
        </properties>
    </persistence-unit>
</persistence>

Note:

-I've added the following property <property name="hibernate.hbm2ddl.auto" value="create"/> to force hibernate to create the table, but still, I get the error saying there is no such table in the database.

-i'm using MySQL as database `


Solution

  • If you are using MySQL5 or above, you can try changing your Dialect to:

    <property name="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</property>