為了儲存 Hibernate 的配置,我們可以使用一個簡單的
hibernate.properties
檔案,或者一個稍微複雜的
hibernate.cfg.xml
,甚至可以完全使用程式來配置 Hibernate,它是hibernate的核心配置檔案。
hibernate.cfg.xml (存放于maven項目的resources檔案夾下)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--資料庫方言,這是指mysql資料庫-->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!--JDBC 驅動程式類。-->
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!--資料庫執行個體的 JDBC URL。-->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/gym
</property>
<!--資料庫使用者名-->
<property name="hibernate.connection.username">
root
</property>
<!--密碼-->
<property name="hibernate.connection.password">
123456
</property>
<!--打開 hbm2ddl.auto 選項将自動生成資料庫模式(schema)- 直接加入資料庫中-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--顯示sql語句-->
<property name="show_sql">true</property>
<!--格式化sql語句-->
<property name="format_sql">true</property>
<!--<property name="hibernate.connection.autocommit">true</property>-->
<!--配置.hbm.xml檔案 ,作用是使用該配置檔案,将實體與資料庫表格對應起來-->
<!-- <mapping resource="com/zy/pojo/Coach.hbm.xml"/>--><!--用于映射檔案-->
<mapping class="com.zy.pojo.Coach"></mapping> <!--用于注解形式-->
</session-factory>
</hibernate-configuration>
mysql資料庫自動建表常見錯誤:
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
修改為:
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
高版本mysql使用:MySQL5Dialect