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 XML Mapping file(hbm.xml)
点击Finish 即可生成ProductionEntity.hbm.xml
打开ProductionEntity.hbm.xml 可以修改里面的内容
有了hbm.xml文件之后需要将其添加到项目的hibernate.cfg.xml中去
<?xml version="1.0" encoding="UTF-8"?> <!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.xml"/> </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 如无意外就会在数据库中生成对应的类了
生成之后的数据库表