卡其 发表于 2016-12-25 00:13

SSH之Hibernate之SchemaExport+配置文件生成表结构

本帖最后由 卡其 于 2016-12-25 00:15 编辑

1、通过SchemaExport跟hibernate的配置文件生成表结构
首先要生成表,得先有实体类,以Person.java为例:

Person类对应的配置文件Person.hbm.xml
<hibernate-mapping>
<class table="T_Person" name="com.tgb.model.Person">
    <id name="id">
      <generator class="native"/>
    </id>
    <property name="name"/>
    <property name="sex"/>
    <property name="address"/>
    <property name="duty"/>
    <property name="phone"/>
    <property name="description"/>
    <many-to-one name="org"></many-to-one>
</class>
</hibernate-mapping>
Person.hbm.xml相关信息的Hibernate默认配置文件,hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/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>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="com/tgb/model/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
最后我们还需要一个根据上述内容生成数据表的小工具,即ExportDB.Java:import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;


public class ExportDB {
          
    /**
   * @param args
   */
    public static void main(String[] args) {
         
      // 默认读取hibernate.cfg.xml文件
      Configuration cfg = new Configuration().configure();
         
      // 生成并输出sql到文件(当前目录)和数据库
      SchemaExport export = new SchemaExport(cfg);
         
      // 创建表结构,第一个true 表示在控制台打印sql语句,第二个true 表示导入sql语句到数据库
      export.create(true, true);
    }
}





页: [1]
查看完整版本: SSH之Hibernate之SchemaExport+配置文件生成表结构