我最近开始使用 Spring 的数据源事务管理器。我现在有个问题。我的事务包括对数据库表的更新和对文件的写入操作。
它工作正常,但我对文件 I/O 有一些疑问。正如您在下面看到的,我已将我的 bean 的 openFile 和 closeFile 方法分别配置为 init-method 和 destroy-method,这反过来又提供了像构造函数和析构函数一样调用这些方法。如果文件没有正确关闭,一些记录可能没有成功写入 output.txt 文件,这意味着我也无法正确处理事务管理。
但是,我想回滚那些尚未附加到平面文件的数据库更新。使用我的解决方案,似乎不可能将 fileClose 方法添加到事务中。有谁知道如何正确实施这个期望的行动?
任何建议将不胜感激
<!--XML CONFIGURATION -->
<bean id="myFileWriter" class="com.job.step.ItemFileWriter" init-method="openFile" destroy-method="closeFile">
<property name="jdbcTemplate" ref="jdbcTemplateProduct"/>
</bean>
public class ItemFileWriter implements ItemWriter<Item> {
private static final Logger log = Logger.getLogger(ItemFileWriter.class);
private BufferedWriter bw = null;
public void openFile() throws IOException {
try {
bw = new BufferedWriter(new FileWriter("C:\\output.txt"));
} catch (IOException e) {
//log.error(e);
throw e;
}
}
public void closeFile() throws IOException {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
log.error(e);
throw e;
}
}
}
@Transactional(rollbackFor = IOException.class)
public void write(List<? extends Item> itemList) throws IOException
{
for (Iterator<? extends Item> iterator = itemList.iterator(); iterator.hasNext();) {
Item item = (Item) iterator.next();
String updateRtlnOutbound = "UPDATE SAMPLESCHEMA.SAMPLETABLE SET STATUS='TRANSFERRED' WHERE ID = ?";
jdbcTemplate.update(updateRtlnOutbound, new Object[]{item.getID()});
String item = String.format("%09d\n", item.customerNumber);
bw.write(item);
}
}
}