java中根據hibernate配置檔案自動建表
1、對與java專案,做資料庫遷移時,都會用的資料指令碼。
2、當引入hibernate時,可以建立資料庫表的配置檔案。可以根據表的配置檔案自動在資料庫建表。(資料庫要預先建立好,因為hibernate只會建表,不會建庫)
步驟:
1)、在配置檔案 hibernate.cfg.cml 中加入引數 ,配置相關資料來源引數和pojo檔案
<property name="hbm2dll.auto">update</property>
<hibernate-configuration><session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">mysecretpassword</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hbm2dll.auto">update</property> <property name="javax.persistence.validation.mode">none</property> <property name="show_sql">true</property> <mapping resource="com/bean/User.hbm.xml"/> <mapping resource="com/bean/Journal.hbm.xml"/> <mapping resource="com/bean/Article.hbm.xml"/> <mapping resource="com/bean/Chapter.hbm.xml"/> <mapping resource="com/bean/Paragraph.hbm.xml"/> </session-factory></hibernate-configuration>
#update 表示自動根據model物件來更新表結構,啟動hibernate時會自動檢查資料庫,如果缺少表,則自動建表;如果表裡缺少列,則自動新增列。
#create:啟動hibernate時,自動刪除原來的表,新建所有的表,所以每次啟動後的以前資料都會丟失。
#create-drop:啟動hibernate時,自動建立表,程式關閉時,自動把相應的表都刪除。所以程式結束時,表和資料也不會再存在。
2)、配置 pojoname.hbm.xml 配置檔案, 新增 hibernate-mapping
<hibernate-mapping> <class name="com.bean.Article" table="article" catalog="test"> <id name="article_id" type="java.lang.Integer"> <column name="article_id"></column> <generator class="identity"></generator> </id> <property name="outline" type="java.lang.String"> <column name="outline" length="20" not-null="false"></column> </property> <property name="title" type="java.lang.String"> <column name="title" length="20" not-null="false"></column> </property> <many-to-one name="journal" class="com.bean.Journal" column="journal_id" not-null="true" cascade="all"></many-to-one> <set name="chapters" inverse="true" cascade="all"> <key column="article_id"></key> <one-to-many class="com.bean.Chapter"></one-to-many> </set> </class> </hibernate-mapping>
3、建立一個啟動類
public class InportDatabase {
public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}
}
即可根據配置檔案在資料庫中建立相應的表。