【hibernate】hibernate对象生成表,web项目和普通项目的hibernate.cfg.xml

注意一、configure()总能找到配置文件,基本不需要自己给它制定路径

Configuration config = new Configuration();//配置对象
config.addFile("src\\main\\resources\\hibernate.cfg.xml");//加载配置文件,其实可有可无
config.configure();//不论什么工程,都会去查到工程目录下的配置文件,应该能找到

注意二、正向工程时,有非基础类型,比如List<String>,尽量不要把这个属性映射到数据库,相应的配置文件中删了它们

http://blog.csdn.net/xyzroundo/article/details/5612693

方法一:在hibernate.cfg.xml中设置<property name="hibernate.hbm2ddl.auto">update</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);//有个严重的问题,先删除原数据表,再新建
    }
}

运行些类实现从自动生成数据库表。

原文地址:https://www.cnblogs.com/549294286/p/2828551.html