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

来源:互联网 发布:java 调用rest api 编辑:程序博客网 时间:2024/06/05 04:05


   初步学习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对话框显示内容如图所示:



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


    


    

0 0