Files
shiro-freemaker-springboot-…/demo-shiro-interface/src/main/java/com/xinwei/utils/Hibernates.java

67 lines
1.9 KiB
Java
Raw Normal View History

2018-02-05 18:59:21 +08:00
package com.xinwei.utils;
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;
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) {
}
}
}
}
}