Hibernate配置文件hibernate.cfg.xml中关于SessionFactory节点配置通常如下:
其中<property name="hbm2ddl.auto">update</property>节点的作用是:"Drop and re-create the database schema on startup".<session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/databaseName</property> <property name="connection.username">usernameDemo</property> <property name="connection.password">passwordDemo</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <!-- Format SQL --> <property name="format_sql">true</property> <mapping resource="com/lemmata/pojo/tableDemo.hbm.xml" /> </session-factory>
Spring整合Hibernate后,可以将Hibernate的SessionFactory完全交给Spring来管理,并且可以使用Spring AOP来实现声明式事务管理。简化Hibernate开发的同时,也可以完全使用Spring配置文件来替代Hibernate的配置文件。
Spring配置文件applicationContext.xml中关于SessionFactory节点的配置通常如下:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="current_session_context_class">thread</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hbm2ddl.auto">update</prop> </props> </property> <!-- 按照文件方式指定 --> <!-- <property name="mappingResources"> <list> <value>com/lemmata/pojo/tableDemo.hbm.xml</value> </list> </property> --> <!-- 按照目录方式指定 --> <property name="mappingDirectoryLocations"> <list> <value>classpath:/com/lemmata/pojo</value> </list> </property> </bean>
其中容易产生问题的地方在于:
<property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="current_session_context_class">thread</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hbm2ddl.auto">update</prop> </props> </property>
有些prop节点的key带有“hibernate”做前缀,有些没有带“ibernate”,而且不同数据库的不同版本对于“<prop key="hbm2ddl.auto">update</prop>”节点是否需要“hibernate”做前缀也有不同的要求,因此如果发现Hibernate某项属性值失效,可在对应属性前补充上“hibernate”字符作为前缀即可。
例如,如果发现Spring整合Hibernate之后没有在加载配置时自动创建数据库架构,解决方法是:可以在<prop key="hbm2ddl.auto">update</prop>节点的key中补充上“hibernate”字符作为前缀即可,如:
<prop key="hibernate.hbm2ddl.auto">update</prop>
在将Spring与Hibernate整合过程中,发现数据库中并未按照预期自动生成表结构。分析可能的原因在于SessionFactory的配置错误。检查hibernate.cfg.xml配置文件,确认相关配置是否正确设置。
572

被折叠的 条评论
为什么被折叠?



