作者:xyzroundo
方法一:在hibernate.cfg.xml中设置<property name="hibernate.hbm2ddl.auto">create</property>,这样做之后部署到应用服务器中,如tomcat等web容器,让web容器加载到hibernate.cfg.xml,从而能自动生成数据库表!
注:怎样让web容器加载到hibernate.cfg.xml?可以用如下方法:
将整合到springContext里如下:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
而springContext是可以在web.xml下面设置监听器的。
方法二:调用hibernate核心里的api,编写一个简单的生成数据库表的类:
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class ExportDB {
public static void main(String[] args) {
//读取配置文件
Configuration cfg = new Configuration().configure("/hibernate.cfg.xml");
//创建SchemaExport对象
SchemaExport export = new SchemaExport(cfg);
//创建数据库表
export.create(true,true);
}
}
运行些类实现从自动生成数据库表。
(当然不管用什么方法,前提是你的实体模型的映射关系要正确无误。任何一个字段或者关系映射有问题都可能生成不了数据库表或者可能生成部分数据库表。)