版本
spring-orm:6.1.3
源码
org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter
java
public class HibernateJpaVendorAdapter extends AbstractJpaVendorAdapter {
// 旧版本Hibernate的方言类是否存在标识
private static final boolean oldDialectsPresent = ClassUtils.isPresent(
"org.hibernate.dialect.PostgreSQL95Dialect", HibernateJpaVendorAdapter.class.getClassLoader());
// jpa方言
private final HibernateJpaDialect jpaDialect = new HibernateJpaDialect();
...
// 构建Jpa属性
private Map<String, Object> buildJpaPropertyMap(boolean connectionReleaseOnClose) {
Map<String, Object> jpaProperties = new HashMap<>();
// 从 spring.jpa.database-platform 属性获取方言类名
if (getDatabasePlatform() != null) {
jpaProperties.put(AvailableSettings.DIALECT, getDatabasePlatform());
}
else {
// 根据 spring.jpa.database 属性获取方言类
Class<?> databaseDialectClass = determineDatabaseDialectClass(getDatabase());
if (databaseDialectClass != null) {
jpaProperties.put(AvailableSettings.DIALECT, databaseDialectClass.getName());
}
}
// 如果设置了 spring.jpa.generate-ddl=true 则设置 hibernate.hbm2ddl.auto=update
if (isGenerateDdl()) {
jpaProperties.put(AvailableSettings.HBM2DDL_AUTO, "update");
}
// 如果设置了 spring.jpa.show-sql=true, 则设置 hibernate.show_sql=true
if (isShowSql()) {
jpaProperties.put(AvailableSettings.SHOW_SQL, "true");
}
// 如果需要在关闭会话时释放连接, 则设置 hibernate.connection.handling_mode=DELAYED_ACQUISITION_AND_HOLD (延迟获取,关闭会话时释放连接)
if (connectionReleaseOnClose) {
jpaProperties.put(AvailableSettings.CONNECTION_HANDLING,
PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_HOLD);
}
// For SpringBeanContainer to be called on Hibernate 6.2
jpaProperties.put("hibernate.cdi.extensions", "true");
return jpaProperties;
}
// 根据数据库类型决定方言类
protected Class<?> determineDatabaseDialectClass(Database database) {
// 根据旧版本Hibernate的方言类是否存在判断Hibernate版本
if (oldDialectsPresent) { // Hibernate版本低于6.2
return switch (database) {
case DB2 -> DB2Dialect.class;
case DERBY -> DerbyTenSevenDialect.class;
case H2 -> H2Dialect.class;
case HANA -> HANAColumnStoreDialect.class;
case HSQL -> HSQLDialect.class;
case INFORMIX -> Informix10Dialect.class;
case MYSQL -> MySQL57Dialect.class;
case ORACLE -> Oracle12cDialect.class;
case POSTGRESQL -> PostgreSQL95Dialect.class;
case SQL_SERVER -> SQLServer2012Dialect.class;
case SYBASE -> SybaseDialect.class;
default -> null;
};
}
else { // Hibernate版本高于6.2(包含)
return switch (database) {
case DB2 -> DB2Dialect.class;
case DERBY -> org.hibernate.dialect.DerbyDialect.class;
case H2 -> H2Dialect.class;
case HANA -> HANAColumnStoreDialect.class;
case HSQL -> HSQLDialect.class;
case MYSQL -> MySQLDialect.class;
case ORACLE -> OracleDialect.class;
case POSTGRESQL -> org.hibernate.dialect.PostgreSQLDialect.class;
case SQL_SERVER -> SQLServerDialect.class;
case SYBASE -> SybaseDialect.class;
default -> null;
};
}
}