您的位置:首页 > 数据库

Hibernate之——使用SchemaExport类自动创建数据库表

2016-07-21 21:43 375 查看
   初步学习Hibernate,对其“使用面向对象的思维操作数据库”理解的越加透彻。
首先入门学习Hibernate的第一步:使用SchemaExport创建数据库表。

一·首先建立实体类:
package com.bjpowernode.hibernate;

import java.util.Date;

public class User1 {

private int id;

private String name;

private String password;

private Date createTime;

private Date expireTime;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public Date getCreateTime() {
return createTime;
}

public void setCreateTime(Date createTime) {
this.createTime = createTime;
}

public Date getExpireTime() {
return expireTime;
}

public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}
}


二·在实体类的基础上,建立对应的映射xml文件:User1.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.bjpowernode.hibernate">
<class name="User1" table="t_user1">
<id name="id" column="user_id" length="32">
<generator class="uuid"/>
</id>
<property name="name" length="30" unique="true" not-null="true"/>
<property name="password"/>
<property name="createTime" type="date" column="create_time"/>
<property name="expireTime"/>
</class>
</hibernate-mapping>

3·在src目录下添加hibernate.cfg.xml配置文件:(该配置文件主要是配置连接数据库的参数)
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>

<mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

四·建立ExportDB类:
package com.bjpowernode.hibernate;

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

/**
* 将hbm生成ddl
* @author Administrator
*
*/
public class ExportDB {

public static void main(String[] args) {

//默认读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}
}

    基础步骤到此结束,首先在MySql创建hibernate_test数据库:
        


       数据库创建成功后,执行ExportDB类的main方法,console对话框显示内容如图所示:



    现在通过命令行查询库里情况:

    


    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: