CriteriaJoinWalker 类:将Criteria中的projection和criterion打包成sql
CriteriaQueryTranslator类:封装实体类属性获取列名,获取查询参数(封装在该类中CriteriaQueryTranslator)值或类型等工具方法
CriteriaImpl 类:封装操作(projection和criterion)及实体信息
实现代码如下:
private String criteriaTranformSql(Criteria criteria)
{
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;//转型
SessionImplementor session = criteriaImpl.getSession();//获取SESSION
SessionFactoryImplementor factory = session.getFactory();//获取FACTORY
CriteriaQueryTranslator translator = new CriteriaQueryTranslator(factory, criteriaImpl, criteriaImpl
.getEntityOrClassName(), CriteriaQueryTranslator.ROOT_SQL_ALIAS);
String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
CriteriaJoinWalker walker = new CriteriaJoinWalker((OuterJoinLoadable) factory
.getEntityPersister(implementors[0]), translator, factory, criteriaImpl, criteriaImpl
.getEntityOrClassName(), session.getLoadQueryInfluencers());
String sql = walker.getSQLString(); //转化成sql语句
//使用参数替换sql中参数占位符?
//获取参数值
Object[] parameters = translator.getQueryParameters().getPositionalParameterValues();
if (sql != null)
{
if (parameters != null && parameters.length > 0)
{
for (Object val : parameters)
{
String value = "%";
if (val instanceof Boolean)
{
value = ((Boolean) val) ? "1" : "0";
}
else if (val instanceof String)
{
value = "'" + val + "'";
}
else if (val instanceof Number)
{
value = val.toString();
}
else if (val instanceof Class)
{
value = "'" + ((Class) val).getCanonicalName() + "'";
}
else if (val instanceof Date)
{
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
value = "'" + sdf.format((Date) val) + "'";
}
else if (val instanceof Enum)
{
value = "" + ((Enum) val).ordinal();
}
else
{
value = val.toString();
}
sql = sql.replaceFirst("\\?", value);
}
}
}
return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
" and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
"!=").replaceAll("<", " < ").replaceAll(">", " > ");
}