使用 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
posted on 2013-10-15 15:41  喜欢凯的蓝  阅读(6163)  评论(0编辑  收藏  举报