我试图将2条sql语句传递给实现itemWriter的java类,以将数据写入posgres DB。我正在尝试通过哈希图做到这一点
<beans:bean id="someItemWriter" scope="step"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<beans:property name="dataSource" ref="someSource" />
<beans:property name="sql" ref = "sqlStatements" >
</beans:property>
<beans:property name="itemPreparedStatementSetter" ref="myPreparedStatementSetter" />
</beans:bean>
参考:
<util:map id = "sqlStatements" map-class= "java.util.HashMap" key-type= "java.lang.String" value-type="java.lang.String">
<beans:entry key = "insert" value ="${fetch.some.sql}"/>
<beans:entry key = "update" value = "${fetch.someAnother.sql}" />
</util:map>
但我收到以下错误:
Cannot convert value of type [java.util.HashMap] to required type [java.lang.String] for property 'sql': no matching editors or conversion strategy found
我做错了什么?我该如何解决?
最佳答案
添加:有时更新/有时插入
好的,鉴于您的评论,您有一个条件,有时要更新,有时要插入。有两种方法可以执行此操作:1)使用单个JdbcBatchItemWriter
并使用MERGE
查询。语法会因数据库而异。 2)使用ClassifierItemWriter
如下所示:
<bean id="classifierWriter" class="org.springframework.batch.item.support.ClassifierCompositeItemWriter">
<property name="classifier">
<bean class="com.package.SimpleClassifier">
<property name="insertWriter" ref="insertWriter" />
<property name="updateWriter" ref="updateWriter" />
</bean>
</property>
</bean>
<bean id="insertWriter" ... />
<bean id="updateWriter" ... />
然后是一个
Classifier
实现,看起来像这样:public class SimpleClassifier implements Classifier<InsertUpdateObject, ItemWriter<? extends InsertUpdateObject>> {
private ItemWriter<? extends InsertUpdateObject> insertWriter;
private ItemWriter<? extends InsertUpdateObject> updateWriter;
@Override
public ItemWriter<? extends InsertUpdateObject> classify(InsertUpdateObject item) {
if (item.getFlag() == 0) {
return insertWriter;
}
return updateWriter;
}
// setters and getters
}
运行多个查询
首先,您不想使用
HashMap
,因为您不能确保SQL的顺序。接下来,您要在此处执行的操作是将多个
JdbcBatchItemWriter
包装在单个CompositeItemWriter
中,如下所示:<bean id="compositeWriter" class="org.springframework.batch.item.support.CompositeItemWriter" scope="step">
<property name="delegates">
<list>
<ref bean="writer1" />
<ref bean="writer2" />
</list>
</property>
</bean>
<bean id="writer1" scope="step"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="someSource" />
<property name="sql" value="${fetch.some.sql}" />
<property name="itemPreparedStatementSetter" ref="myPreparedStatementSetter" />
</bean>
<bean id="writer2" scope="step"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="someSource" />
<property name="sql" value="${fetch.someAnother.sql}" />
<property name="itemPreparedStatementSetter" ref="myPreparedStatementSetter" />
</bean>
这将允许您列出所需的语句,并确保它们以指定的顺序运行。