Freemarker实现Hibernate动态sql

主ftl文件:

${***}为全局变量,即在获取free marker时传入的数据

通过import导入其他的ftl文件

<#import "join-table.ftl" as joinSpace>
<#import "where-condition.ftl" as conditionSpace>
<#import "main-where-condition.ftl" as mainConditionSpace>

select distinct table1.* from(
select
    table.*
from
    ${defaultSchema}.tablename table
where cors1.ACTIVE_IND = 'A'
<#-- where condition -->
<@mainConditionSpace.condition />
) table1
<@joinSpace.join />
<#-- where condition -->
where 1=1
<@conditionSpace.condition />
order by table1.${sortField} ${direction}

join文件:

<#-- join table -->
<#macro join>
<#if string?? && string!= "">
    join sql
</#if>
<#if boolean??>
    join sql
</#if>
<#if list?? && (list?size > 0)>
    join sql
</#if>
</#macro>

where文件:

<#-- where condition -->
<#macro condition>
<#if string?? && string!= "">
    condition sql
</#if>
<#if list?? && (list?size > 0)>
    condition sql
</#if>
</#macro>

获取freemarker及执行sql:

public class FreeMarkerTemplate {
    private  static final Logger log = LoggerFactory.getLogger(FreeMarkerTemplate.class);

    private static Configuration configuration;

    static {
        configuration = new Configuration(Configuration.getVersion());

        //set default directory of templates
        configuration.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplate.class, "/templates/"));

        //set default schema variable for all sql templates
        try {
            configuration.setSharedVariable("defaultSchema", SCHEMA);
        } catch (TemplateModelException e) {
            log.error("set shared variable error:{}", ExceptionUtils.getStackTrace(e));
        }
    }

    public String getSqlFromTemplate(Object data, String templateName) {
        if (Objects.isNull(configuration))
            return StringUtils.EMPTY;

        //if setting default database schema failed, return empty string when getting sql string from templates
        TemplateModel defaultSchema = configuration.getSharedVariable("defaultSchema");

        if (Objects.isNull(defaultSchema) || StringUtils.isEmpty(defaultSchema.toString())) {
            return StringUtils.EMPTY;
        }

        try {
            Template template = configuration.getTemplate(templateName);
            try(StringWriter writer = new StringWriter()) {
                template.process(data, writer);
                return writer.toString();
            }
        } catch (TemplateNotFoundException templateNotFoundException) {
            log.error("templates not found:{}", ExceptionUtils.getStackTrace(templateNotFoundException));
            return StringUtils.EMPTY;
        } catch (TemplateException templateException) {
            log.error("templates exception:{}", ExceptionUtils.getStackTrace(templateException));
            return StringUtils.EMPTY;
        } catch (IOException ioException) {
            log.error("IO Exception:{}", ExceptionUtils.getStackTrace(ioException));
            return StringUtils.EMPTY;
        }
    }

}

通过文件名获取template并执行 

String sqlFromTemplate = template.getSqlFromTemplate(filterDto, CorsSpecificationKey.TEMPLATE_NAME_FOR_CORS);
        String queryForCount = template.getSqlFromTemplate(filterDto, CorsSpecificationKey.TEMPLATE_NAME_FOR_CORS_COUNT);
        Query query = QueryUtils.applyNamedParameters(entityManager.createNativeQuery(sqlFromTemplate, Correspondence.class), filterDto);
        Query countQuery = QueryUtils.applyNamedParameters(entityManager.createNativeQuery(queryForCount), filterDto);
        query.setFirstResult(filterDto.getPage() * filterDto.getSize());
        query.setMaxResults(filterDto.getSize());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值