Hibernate auto create database

后端 未结 4 1561
花落未央
花落未央 2020-12-02 20:19

I have a Java EE Hibernate project, and I\'m using MySQL as a database.

I want that when I first time run the project, it will create the database automatically.

相关标签:
4条回答
  • 2020-12-02 20:56

    <property name="hibernate.hbm2ddl.auto">create</property> will create tables. But it will not create database. Change the connection url to generate the database.

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost/InternetProject?createDatabaseIfNotExist=true</property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>
    <property name="connection.pool_size">10</property>
    

    Update : character encoding when creating database

    <property name="connection.url">
        jdbc:mysql://localhost/InternetProject?createDatabaseIfNotExist=true&useUnicode=yes&characterEncoding=UTF-8
    </property>
    
    0 讨论(0)
  • 2020-12-02 21:10

    There are multiple option for auto property.

    1. create - It creates new tables corresponding mapping or annotation. It drops existing tables and data.
    2. update - It keeps existing data and tables. It updates schema. here we have to take care contrants.
    3. create-drop - It is same like create but once session gets closed it drops everything.
    4. validate - it validates or matches schema with map or annotation. It's valid for Production environment.

      <!-- create create-drop validate update -->
      <property name="hbm2ddl.auto">update</property>
      

    I hope it helps.

    0 讨论(0)
  • 2020-12-02 21:11
    <property name="hibernate.hbm2ddl.auto">create</property>
    

    will do

    0 讨论(0)
  • 2020-12-02 21:17

    Hibernate will not create the database for you, only the tables. To create the database you need to tell MySQL to create it if it does'nt already exist by adding a parameter to the URL. E.g.:

    jdbc:mysql://db:3306/mydatabase?createDatabaseIfNotExist=true
    
    0 讨论(0)
提交回复
热议问题