使用schemaExport自动生成表结构

来源:互联网 发布:淘宝买家留言怎么修改 编辑:程序博客网 时间:2024/04/30 15:55

一.Hibernate原生状态

 

?
1
2
3
4
5
Configuration cfg = newConfiguration().configure();
 
SchemaExport export = newSchemaExport(cfg);
 
export.create(true,true);

 

二.Hibernate整合Spring


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


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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
Spring applicationContext.xml
 
<beanid="sessionFactory"
 
   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 
      <propertyname="configLocation"
 
        value="file:src/hibernate.cfg.xml">
 
      </property>
 
</bean>


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


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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
ClassPathResource ac = newClassPathResource("applicationContext.xml");
 
     XmlBeanFactory xbf = newXmlBeanFactory(ac);
 
     //注意: &sessionFactory ,一定要包含 & ,不加Spring返回的是Hibernate下的SessionFactoryImpl类
 
     LocalSessionFactoryBean lsfb=(LocalSessionFactoryBean) xbf.getBean("&sessionFactory");
 
     Configuration cfg=lsfb.getConfiguration();
 
     SchemaExport export=newSchemaExport(cfg);
 
     export.create(true,false);



?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!-- 配置数据源-->
 
 <beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 
    <propertyname="driverClassName"value="${jdbc.driverClassName}"/>
 
      <propertyname="url"value="${jdbc.url}"/>
 
      <propertyname="username"value="${jdbc.username}"/>
 
      <propertyname="password"value="${jdbc.password}"/>
 
 </bean>
 
 
 
 <!-- 配置sessionfactory,该配置替代了hibernate.cfg.xml的配置 -->
 
 <beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 
    <propertyname="dataSource"ref="dataSource"></property>
 
    <propertyname="mappingResources">
 
      <list>
 
         <value>xxx/xxx/model/User.hbm.xml</value>
 
      </list>
 
    </property>
 
    <propertyname="hibernateProperties">
 
      <props>
 
         <propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
 
         <propkey="hibernate.show_sql">true</prop>
 
         <propkey="hibernate.format_sql">true</prop>
 
      </props>
 
    </property>
 
 </bean>
0 0
原创粉丝点击