Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

java - Hibernate auto create database

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.

This is my hibernate.cnf.xml:

<?xml version='1.0' encoding='utf-8' ?>

<!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/InternetProject</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">10</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <mapping class="entities.Business" />
        <mapping class="entities.Coupon" />
        <mapping class="entities.User" />
        <mapping class="entities.LastLogin" />
    </session-factory>  
</hibernate-configuration>

When I first time run this project on another computer, how can I make the database InternetProject to be created?

According to the config file, it might already do it and I'm not aware to it.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...