Hibernate整合Spring後,如何使用SchemaExport生成數據庫表

SchemaExport生成數據庫表java


一.Hibernate原生狀態

 

Configuration cfg = new Configuration().configure();

SchemaExport export = new SchemaExport(cfg);

export.create(true, true);

 

二.Hibernate整合Spring


       1.使用hibernate.cfg.xml原生配置


              hibernate.cfg.xml同原生同樣編寫spring

              Spring主配置文件applicationContext中,引入hibernate.cfg.xmlsql

             使用SchemaExport生成數據庫表的代碼同上一致。數據庫

Spring applicationContext.xml

<bean id="sessionFactory"

   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

      <property name="configLocation"

        value="file:src/hibernate.cfg.xml">

      </property>

</bean>


       2.不使用hibernate.cfg.xml,Spring的主配置文件applicationContext.xml中配置


              徹底不編寫hibernate.cfg.xml,所有都在applicationContext.xml中配置   session

ClassPathResource ac = new ClassPathResource("applicationContext.xml");

      XmlBeanFactory xbf = new XmlBeanFactory(ac);

      //注意: &sessionFactory ,必定要包含 & ,不加Spring返回的是Hibernate下的SessionFactoryImpl類

      LocalSessionFactoryBean lsfb=(LocalSessionFactoryBean) xbf.getBean("&sessionFactory");

      Configuration cfg=lsfb.getConfiguration();

      SchemaExport export=new SchemaExport(cfg);

      export.create(true, false);



<!-- 配置數據源-->

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

      <property name="driverClassName" value="${jdbc.driverClassName}"/>

        <property name="url" value="${jdbc.url}"/>

        <property name="username" value="${jdbc.username}"/>

        <property name="password" value="${jdbc.password}"/>

   </bean>

  

   <!-- 配置sessionfactory,該配置替代了hibernate.cfg.xml的配置 -->

   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

      <property name="dataSource" ref="dataSource"></property>

      <property name="mappingResources">

        <list>

           <value>xxx/xxx/model/User.hbm.xml</value>

        </list>

      </property>

      <property name="hibernateProperties">

        <props>

           <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

           <prop key="hibernate.show_sql">true</prop>

           <prop key="hibernate.format_sql">true</prop>

        </props>

      </property>

   </bean>
相關文章
相關標籤/搜索