基于Freemarker动态SQL构造工具

本文旨在介绍如何使用Freemarker作为动态SQL构造工具,将SQL语句编写在XML中,通过Java代码传入参数并利用Freemarker处理,以实现SQL的动态构建和提高代码可读性。同时,Freemarker的include语句还能帮助提取和复用公共SQL片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.目的

将sql语句编写的xml中,然后在java代码中,传入参数,经过freemarker处理,得到处理完的SQL. 好处:

  • sql编写在xml中,便于阅读
  • 可以使用freemarker语法,动态构建SQL
  • 可以使用freemarker的include语句,提取公用SQL

 

 

 

三.使用指南

 

maven

 

        <groupId>com.duowan.common</groupId>
        <artifactId>duowan-common-util</artifactId>
        <version>1.0.11</version>       

 

spring配置

 

        <bean id="sqlFreeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean" >
        <property name="preTemplateLoaders" >
                <bean id="templateLoader" class="com.duowan.common.freemarker.loader.MapTemplateLoader">
                                <property name="templateMap" ref="sqlTemplateProperties"></property>
                </bean>
        </property>
        </bean>
        
    <bean id="sqlTemplateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="ignoreResourceNotFound" value="true" />
                <property name="locations">
                        <list>
                                <value>classpath*:/freemarker_sql/**/*.xml</value>
                        </list>
                </property>
    </bean>

 

xml配置中编写SQL

user.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>

        <entry key="user.delete">
                <![CDATA[
                delete from user where id=:id
                ]]>
        </entry>
        
        <entry key="user.select">
                <![CDATA[
                select * from user
                <#include "userWhere">
                ]]>
        </entry>
        
        <entry key="userWhere">
                <![CDATA[
                1=1
                ]]>
        </entry>
        
</properties>

 

java代码

 

 

        @Test
        public void test() throws IOException, TemplateException {
                Map model = new HashMap();
                model.put("name", "badqiu");
                model.put("sex", 1);
                model.put("age", 100);
                
                ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-freemarker-sql.xml");
                Configuration conf = (Configuration)ac.getBean("sqlFreeMarkerConfiguration");
                String sql = FreeMarkerTemplateUtils.processTemplateIntoString(conf.getTemplate("user.select"), model);
                System.out.println(sql);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值