26.3. 方言的使用
最开始,Hibernate 总是要求用户指定所使用的方言(dialect)。在用户希望同时使用多个数据库时就会出现问题。通常这要求用户配置 Hibernate 方言或者定义自己设置这个值的方法。
从版本 3.2 开始,Hibernate 引入了方言的自动检测,它基于从该数据库的
java.sql.Connection
上获得的 java.sql.DatabaseMetaData
。这是一个更好的方案,但它局限于 Hibernate 已知的数据库且无法进行配置和覆盖。
Starting with version 3.3, Hibernate has a fare more powerful way to automatically determine which dialect to should be used by relying on a series of delegates which implement the
org.hibernate.dialect.resolver.DialectResolver
which defines only a single method:
<!-- <br/> --><span class="java_keyword">public</span><!-- <br/> --><span class="java_plain"> </span><!-- <br/> --><span class="java_type">Dialect</span><!-- <br/> --><span class="java_plain"> resolveDialect</span><!-- <br/> --><span class="java_separator">(</span><!-- <br/> --><span class="java_type">DatabaseMetaData</span><!-- <br/> --><span class="java_plain"> metaData</span><!-- <br/> --><span class="java_separator">)</span><!-- <br/> --><span class="java_plain"> </span><!-- <br/> --><span class="java_keyword">throws</span><!-- <br/> --><span class="java_plain"> </span><!-- <br/> --><span class="java_type">JDBCConnectionException</span>
. The basic contract here is that if the resolver 'understands' the given database metadata then it returns the corresponding Dialect; if not it returns null and the process continues to the next resolver. The signature also identifies
org.hibernate.exception.JDBCConnectionException
as possibly being thrown. A JDBCConnectionException here is interpreted to imply a "non transient" (aka non-recoverable) connection problem and is used to indicate an immediate stop to resolution attempts. All other exceptions result in a warning and continuing on to the next resolver.
这 些解析者最棒的功能是用户也可以注册自定义的解析者,它们将在内置的解析者之前被调用。在许多情况下这可能很有用:它可以轻易地集成内置方言之外的方言的 自动检测;它让你可以使用自定义的方言等。要注册一个或多个解析者,只要用 'hibernate.dialect_resolvers' 配置设置指定它们(由逗号、制表符或空格隔开)就可以了(请参考
org.hibernate.cfg.Environment
上的 DIALECT_RESOLVERS
)。