1. 程式人生 > >使用 hibernate 根據對映檔案生成資料庫表

使用 hibernate 根據對映檔案生成資料庫表

為了更好的顯示效果,可以在hibernate.cfg.xml配置檔案的<session-factory>標籤里加入以下內容:

顯示sql語句和格式化顯示sql語句:

<property name="show_sql">true</property>
<property name="format_sql">true</property>

方法一:使用SchemaExport

對映檔案Student.hbm.xml:

複製程式碼
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
> <hibernate-mapping package="accp.hibernate"> <class name="Student" table="Student"> <id name="id" column="id"> <generator class="native" /> </id> <property name="name" type="java.lang.String" column="name" /> <
property name="birthDay" type="java.util.Date" column="birthday" /> </class> </hibernate-mapping>
複製程式碼

對應的實體類,Student.java

複製程式碼
package accp.hibernate;

import java.util.Date;

public class Student{
    private Integer id;
    private String name;
    private Date birthDay;
    //省略get,set方法......
}
複製程式碼

關鍵程式碼!使用SchemaExport生成表的程式碼如下:

Test.java:

複製程式碼
package accp.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Test {
    public static void main(String[] args) {
        Configuration conf = new Configuration().configure();   //讀取並解析配置檔案
        SchemaExport export=new SchemaExport(conf);   //建立SchemaExport
        //執行生成表。引數1:是否顯示sql語句,引數2:是否到資料庫裡執行
        export.create(true, true);  
    }
}
複製程式碼

方法二:配置<property name="hbm2ddl.auto">屬性

在hibernate.cfg.xml配置檔案的<session-factory>標籤里加入以下內容:

<property name="hbm2ddl.auto">create</property>

<property name="hbm2ddl.auto">的選項有:validate | update | create | create-drop

areate 如果資料庫裡沒這張表,則自動建立。
update 配置檔案裡的表結構發生改變,重新建立該表。
create-drop

在顯式關閉SessionFactory 時,將刪除掉資料庫 schema。

validate 驗證,每次對資料庫表作操作時驗證是否和對映檔案的結構對應上。

配置完成後。只要在程式裡對該“表”進行操作,hibernate就會自動建立該表。如Test.java:

以上兩種方法都能根據對映檔案往資料庫中建立表,並在控制檯中打印出如下sql建表語句:

複製程式碼
Hibernate: 
    drop sequence hibernate_sequence
Hibernate: 
    create table Student (
        id number(10,0) not null,
        name varchar2(255 char),
        birthday timestamp,
        primary key (id)
    )
Hibernate: 
    create sequence hibernate_sequence
複製程式碼

========================================================================================

補充:在hibernate自動建立表時新增約束

需要在hibernate建立表時新增約束的話,可以在對映檔案相應欄位的property裡新增<column>子元素。如name欄位:

<property name="name" type="java.lang.String">
    <column name="name"></column>
</property>

在<column>標籤裡新增相應的屬性即可,如設定name列的長度為10,只能以a開頭:

<property name="name" type="java.lang.String">
    <column name="name" length="10" check="name like 'a%'"></column>
</property>

這時,hibernate打印出來的sql語句為:

複製程式碼
drop table Student cascade constraints

    drop sequence hibernate_sequence

    create table Student (
        id number(10,0) not null,
        name varchar2(10 char) check (name like 'a%'),
        birthday timestamp,
        primary key (id)
    )

    create sequence hibernate_sequence