/** * @author xichao.dong * @email 406592176@qq.com * @date 2014-8-15 上午8:50:38 * @company (开发公司) 珠海市冰川软件有限公司 * @copyright (版权) 本文件归属珠海市冰川软件有限公司所有 * @version V1.0 * @modify (修改) : 2014-8-15 上午8:50:38 xichao.dong * @Review (审核人) :xichao.dong */ package com.glacier.basic.util; 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; /** * @ClassName: Hibernates * @Description: TODO(这里用一句话描述这个类的作用) * @author xichao.dong * @email 406592176@qq.com * @date 2014-8-15 上午11:15:19 */ public class Hibernates { public static final String DATETIME_TYPE = "org.jadira.usertype.dateandtime.joda.PersistentDateTime"; /** * Initialize the lazy property value. * * eg. * Hibernates.initLazyProperty(user.getGroups()); */ public static void initLazyProperty(Object proxyedPropertyValue) { Hibernate.initialize(proxyedPropertyValue); } /** * 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型. * 仅支持Oracle, H2, MySql,如需更多数据库类型,请仿照此类自行编写。 */ public static String getDialect(DataSource dataSource) { String jdbcUrl = getJdbcUrlFromDataSource(dataSource); // 根据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 of " + jdbcUrl); } } private static String getJdbcUrlFromDataSource(DataSource dataSource) { Connection connection = null; try { connection = dataSource.getConnection(); if (connection == null) { throw new IllegalStateException("Connection returned by DataSource [" + dataSource + "] was null"); } return 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) { } } } } }