zoukankan      html  css  js  c++  java
  • 【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);//有个严重的问题,先删除原数据表,再新建
        }
    }

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

  • 相关阅读:
    【Spring-MVC】
    【多线程】线程池关闭
    【DDD】基于事件驱动EDA -- 待完成
    【DDD】编码实战
    【Elastic Search】01- 原理
    【DDD】基于DDD的分层设计
    【DDD】Thoughtworks笔记(编码样例) -- 未完成
    【DDD】Thoughtworks笔记(目录划分、异常设计)
    平方和求余
    Factoring a Polynomial
  • 原文地址:https://www.cnblogs.com/549294286/p/2828551.html
Copyright © 2011-2022 走看看