我使用以下spring应用程序上下文:
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<!--
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
-->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider}</prop>
<prop key="hibernate.connection.pool_size">10</prop>
<prop key="hibernate.jdbc.batch_size">1000</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
...
</list>
</property>
<property name="schemaUpdate" value="${hibernate.schemaUpdate}"/>
</bean>
然后问题是:虽然Hibernate应该支持Dialect-Autodetection,但是这段代码不起作用: Uppon Application-Init抛出以下异常:
org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.
at org.hibernate.dialect.Dialect.instantiateDialect(Dialect.java:256)
at org.hibernate.dialect.Dialect.getDialect(Dialect.java:234)
at org.hibernate.dialect.Dialect.getDialect(Dialect.java:249)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean$3.doInHibernate(LocalSessionFactoryBean.java:957)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:339)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.updateDatabaseSchema(LocalSessionFactoryBean.java:953)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.afterSessionFactoryCreation(LocalSessionFactoryBean.java:843)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:213)
我可以通过取消注释hibernate.dialect属性来避免此异常。为什么我要这样做?为什么不能休眠只是自动检测方言?
我想删除dialect-property来解决this问题。
答案 0 :(得分:6)
Hibernate本身尝试在Configuration.buildSessioNFactory()
通话期间自动检测方言 - 通常(尽管并非总是如此)成功。
Spring代码没有 - 这就是你获得异常的地方。 LocalSessionFactoryBean.updateDatabaseSchema()
方法使用Dialect.getDialect()
方法获取Dialect
实例,该实例需要明确设置方言。
我不太清楚为什么会这样做,虽然我怀疑这是防止Hibernate错误地检测你的方言错误并且弄乱你的数据库的预防措施(因为更新架构可能是非常灾难性的)。
您的选择是:
schemaUpdate
设为false updateDatabaseSchema()
方法以从会话工厂实例中获取(已经自动检测到的)方言。你必须将它强制转换为SessionFactoryImplementor:
public void updateDatabaseSchema() throws DataAccessException {
final Dialect dialect = ((SessionFactoryImplementor) getSessionFactory()).getDialect();
...
hibernateTemplate.execute(new HibernateCallback() {
...
// you already have the dialect so you don't need to get it using this:
// Dialect dialect = Dialect.getDialect(getConfiguration().getProperties());
...
);
}