hibernate 整合spring 后使用schemaExport生成数据库

SchemaExport生成数据库表

 

一.Hibernate原生状态

 

1 Configuration cfg = new Configuration().configure();
2  
3 SchemaExport export = new SchemaExport(cfg);
4  
5 export.create(truetrue);

 

 

 

二.Hibernate整合Spring

 

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

 

              hibernate.cfg.xml同原生一样编写

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

             使用SchemaExport生成数据库表的代码同上一致。

01 Spring applicationContext.xml
02  
03 <bean id="sessionFactory"
04  
05    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
06  
07       <property name="configLocation"
08  
09         value="file:src/hibernate.cfg.xml">
10  
11       </property>
12  
13 </bean>

 

 

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

 

              完全不编写hibernate.cfg.xml,全部都在applicationContext.xml中配置   

 

01 ClassPathResource ac = new ClassPathResource("applicationContext.xml");
02  
03      XmlBeanFactory xbf = new XmlBeanFactory(ac);
04  
05      //注意: &sessionFactory ,一定要包含 & ,不加Spring返回的是Hibernate下的SessionFactoryImpl类
06  
07      LocalSessionFactoryBean lsfb=(LocalSessionFactoryBean) xbf.getBean("&sessionFactory");
08  
09      Configuration cfg=lsfb.getConfiguration();
10  
11      SchemaExport export=new SchemaExport(cfg);
12  
13      export.create(truefalse);

 

 

 

 

01 <!-- 配置数据源-->
02  
03  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
04  
05     <property name="driverClassName" value="${jdbc.driverClassName}"/>
06  
07       <property name="url" value="${jdbc.url}"/>
08  
09       <property name="username" value="${jdbc.username}"/>
10  
11       <property name="password" value="${jdbc.password}"/>
12  
13  </bean>
14  
15  
16  
17  <!-- 配置sessionfactory,该配置替代了hibernate.cfg.xml的配置 -->
18  
19  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
20  
21     <property name="dataSource" ref="dataSource"></property>
22  
23     <property name="mappingResources">
24  
25       <list>
26  
27          <value>xxx/xxx/model/User.hbm.xml</value>
28  
29       </list>
30  
31     </property>
32  
33     <property name="hibernateProperties">
34  
35       <props>
36  
37          <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
38  
39          <prop key="hibernate.show_sql">true</prop>
40  
41          <prop key="hibernate.format_sql">true</prop>
42  
43       </props>
44  
45     </property>
46  
47  </bean>
posted @ 2013-03-18 10:45  眉间尺之魂  阅读(228)  评论(0编辑  收藏  举报