问题
Is there a simple way to externalize big sql queries from jdbc outbound gateways, instead of inlining it? The reason being that we're having to many big queries to make, and we'd like to have them on their own files, or at least externalize them in beans.
Some caveats:
- I don't have control over the database, so I can't create anything there (e.g. stored procedures)
- I don't want to create classes just for this matter, I just want to organize/refactor it a bit, and not make it more complex introducing many other steps
- I'd prefer to create bare .sql files, but putting the queries in an xml withing a bean is okay too
- I don't have the option of using hibernate, stuck to spring integration jdbc
Suggestions on how to better organize this, considering that we're going to have many others outbound gateways are welcome :)
For instance, I wouldn't like to have the SQL inline in the "int-jdbc:outbound-gateway" element as follows:
<int-jdbc:outbound-gateway
data-source="datasource"
request-channel="reqChannel"
reply-channel="respChannel"
row-mapper="datamapper" max-rows-per-poll="1000"
query=" SELECT Field1, Field2, ManyOthers
FROM Table T
JOIN A ON A.id = T.id [... many other joins here ...]
WHERE SOMECONDITION=:payload">
</int-jdbc:outbound-gateway>
What I've done using the answers
Simply:
<bean id="myCoolQuery" class="java.lang.String">
<constructor-arg>
<value>
<![CDATA[
SELECT Field1, Field2, ManyOthers
FROM Table T
JOIN A ON A.id = T.id [... many other joins here ...]
WHERE SOMECONDITION=:payload
]]>
</value>
</constructor-arg>
</bean>
<int-jdbc:outbound-gateway
data-source="datasource"
request-channel="reqChannel"
reply-channel="respChannel"
row-mapper="datamapper" max-rows-per-poll="1000"
query="#{myCoolQuery}">
</int-jdbc:outbound-gateway>
It also works with the ":payload" parameter used inside the bean.
回答1:
You can define your queries in XML as spring beans:
<bean id="exampleQuerySql" class="java.lang.String">
<constructor-arg>
<value>
<![CDATA[
select * from foo
where whatever_ind = 'A'
]]>
</value>
</constructor-arg>
</bean>
Using CDATA the query text can include newlines, angle brackets, etc., so it's legible and you can cut and paste it directly into a SQL tool.
You can refer to the bean using SpEL.
回答2:
Yes, you can put them in a properties file, and use properties placeholders ${...} to resolve them, or you can use SpEL...
"#{myQueryBean.queryOne}"
where myQueryBean is a <bean/> that's an instance of a class with a method...
public String getQueryOne() {...}
or a static constant on a class...
"#{T(foo.Queries).QUERY_ONE}"
public static final String QUERY_ONE = "...";
来源:https://stackoverflow.com/questions/25556825/spring-integration-externalizing-jdbc-queries