public class QueryBuilderVelocity implements QueryBuilder, ApplicationContextAware {
/** logger */
private static final Logger logger = LoggerFactory.getLogger(QueryBuilderVelocity.class);
/** Velocity引擎 */
protected VelocityEngine velocityEngine;
/** Spring上下文 */
protected ApplicationContext applicationContext;
public String getQueryString(String queryName, Map<String, ?> conditions) {
String queryTemplate = (String) this.applicationContext.getBean(queryName);
if (queryTemplate == null) {
throw new AppException(ErrorCode.ERROR_QUERY_TEMPLATE_NOT_EXIST, "查询模板不存在!");
}
try {
Context context = new VelocityContext(conditions);
StringWriter queryStringWriter = new StringWriter();
this.velocityEngine.evaluate(context, queryStringWriter, "", queryTemplate);
return queryStringWriter.toString();
} catch (Exception ex) {
logger.error("Velocity引擎生成查询语句出错!", ex);
throw new AppException(ErrorCode.ERROR_BUILD_QUERY_STRING, "Velocity引擎生成查询语句出错!", ex);
}
}
/**
* 设置Velocity引擎
* @param velocityEngine Velocity引擎
*/
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
/**
* 设置Spring上下文
* @param applicationContext Spring上下文
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}