你的位置:首页 > Java教程

[Java教程]Hibernate生成数据库表


首先创建实体类

import java.util.Date;public class ProductionEntity {  public Integer getId() {    return id;  }  public void setId(Integer id) {    this.id = id;  }  public String getOrigin() {    return origin;  }  public void setOrigin(String origin) {    this.origin = origin;  }  public Double getPrice() {    return price;  }  public void setPrice(Double price) {    this.price = price;  }  public Date getDate() {    return date;  }  public void setDate(Date date) {    this.date = date;  }  private Integer id;  private String origin;  private Double price;  private Date date;}

然后Eclipse中在实体类上右键New-Other-Hibernate-Hibernate

SNAP1474

SNAP1475

点击Finish 即可生成ProductionEntity.hbm.

打开ProductionEntity.hbm.

有了hbm.

<??><!DOCTYPE hibernate-configuration PUBLIC    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>  <session-factory>    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>    <property name="hibernate.connection.password">12345678</property>    <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>    <property name="hibernate.connection.username">root</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/Mageric/entity/ExchangeEntity.hbm./>   </session-factory></hibernate-configuration>

有了实体类和对应的Hibernate配置文件后还需要一个ExportDB类 来生成数据库表

import org.hibernate.boot.MetadataSources;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.boot.spi.MetadataImplementor;import org.hibernate.service.ServiceRegistry;import org.hibernate.tool.hbm2ddl.SchemaExport;public class ExportDB {  /**   * @param args   */  public static void main(String[] args) {    ServiceRegistry serviceRegistry = (ServiceRegistry) new StandardServiceRegistryBuilder().configure().build();    MetadataImplementor metadataImplementor = (MetadataImplementor) new MetadataSources(serviceRegistry)        .buildMetadata();    SchemaExport export = new SchemaExport(serviceRegistry, metadataImplementor);    export.create(true, true);  }}

Hibernate 5.X的代码跟之前的有些出入 旧的方法已经不再推荐使用了

有了上面两个类和配置文件之后就可以运行ExportDB.java 如无意外就会在数据库中生成对应的类了

SNAP1476

生成之后的数据库表

image