org.simpleflatmapper.jdbc.impl.SelectQueryWhereFactory Maven / Gradle / Ivy
Show all versions of sfm-jdbc Show documentation
package org.simpleflatmapper.jdbc.impl;
import org.simpleflatmapper.jdbc.JdbcMapper;
import org.simpleflatmapper.jdbc.JdbcMapperFactory;
import org.simpleflatmapper.jdbc.QueryPreparer;
import org.simpleflatmapper.jdbc.named.NamedSqlQuery;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class SelectQueryWhereFactory {
private final CrudMeta meta;
private final JdbcMapperFactory jdbcMapperFactory;
private final JdbcMapper jdbcMapper;
private final ConcurrentMap> cache = new ConcurrentHashMap>();
public SelectQueryWhereFactory(CrudMeta meta, JdbcMapper jdbcMapper, JdbcMapperFactory jdbcMapperFactory) {
this.meta = meta;
this.jdbcMapper = jdbcMapper;
this.jdbcMapperFactory = jdbcMapperFactory;
}
@SuppressWarnings("unchecked")
public SelectQueryImpl where(String whereClause, Type paramClass) {
SelectQueryKey key = new SelectQueryKey(whereClause, paramClass);
SelectQueryImpl selectQuery = cache.get(key);
if (selectQuery == null) {
SelectQueryImpl newSelectQuery = newSelectQuery(whereClause, paramClass);
selectQuery = cache.putIfAbsent(key, newSelectQuery);
if (selectQuery == null) {
selectQuery = newSelectQuery;
}
}
return (SelectQueryImpl) selectQuery;
}
private SelectQueryImpl newSelectQuery(String whereClause, Type paramClass) {
String query = sqlQuery(whereClause);
QueryPreparer queryPreparer = jdbcMapperFactory.
from(paramClass).to(NamedSqlQuery.parse(query));
return new SelectQueryImpl(queryPreparer, jdbcMapper);
}
private String sqlQuery(String whereClause) {
StringBuilder sb = new StringBuilder("SELECT * FROM ");
meta.appendTableName(sb);
sb.append(" WHERE ");
sb.append(whereClause);
return sb.toString();
}
private static class SelectQueryKey {
private final String query;
private final Type type;
private SelectQueryKey(String query, Type type) {
this.query = query;
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SelectQueryKey that = (SelectQueryKey) o;
if (!query.equals(that.query)) return false;
return type.equals(that.type);
}
@Override
public int hashCode() {
int result = query.hashCode();
result = 31 * result + type.hashCode();
return result;
}
}
}