package com.fang.bbks.common.persistence; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.lang3.StringUtils; import org.hibernate.Hibernate; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.MySQL5InnoDBDialect; import org.hibernate.dialect.Oracle10gDialect; /** * Hibernates 工具类 * @version 2013-01-15 */ public class Hibernates { /** * Initialize the lazy property value, eg. * Hibernates.initLazyProperty(user.getRoles()); */ public static void initLazyProperty(Object proxyedPropertyValue) { Hibernate.initialize(proxyedPropertyValue); } /** * 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型. */ public static String getDialect(DataSource dataSource) { //从DataSource中取出jdbcUrl. String jdbcUrl = null; Connection connection = null; try { connection = dataSource.getConnection(); if (connection == null) { throw new IllegalStateException("Connection returned by DataSource [" + dataSource + "] was null"); } jdbcUrl = connection.getMetaData().getURL(); } catch (SQLException e) { throw new RuntimeException("Could not get database url", e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { connection = null; } } } //根据jdbc url判断dialect if (StringUtils.contains(jdbcUrl, ":h2:")) { return H2Dialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":mysql:")) { return MySQL5InnoDBDialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":oracle:")) { return Oracle10gDialect.class.getName(); } else { throw new IllegalArgumentException("Unknown Database"); } } }