PostgreSQLとMySQLでランダムにデータを取り出すとき、
MySQLだと
ORDER BY rand()
PostgreSQLだと
ORDER BY RANDOM()
になりますが、これをPlay FrameworkのEBeanでデータベースエンジンを判別して振り分ける方法です。
public static String getDatabase() {
try {
DataSource dataSource = DB.getDataSource();
Connection connection2 = dataSource.getConnection();
DatabaseMetaData metaData = connection2.getMetaData();
return metaData.getDatabaseProductName();
} catch (SQLException e) {
Logger.error("getDatabase", e);
}
return "";
}
この方法でデータベースエンジンを取得することができます。
なおメタデータではデータベースエンジンのバージョン情報なども取得可能なようです。
MySQLかどうか、PostgreSQL可動化を判別するには以下のようにします。
public static boolean isMySQL() {
return "mysql".equalsIgnoreCase(getDatabase()) ? true : false;
}
public static boolean isPostgreSQL() {
return "postgresql".equalsIgnoreCase(getDatabase()) ? true : false;
}
データベースエンジンごとにランダムを返すには
public static String getRandom() {
if (isMySQL()) {
return "RAND()";
} else if (isPostgreSQL()) {
return "RANDOM()";
}
return "";
}


