首页 文章

Spring批处理有条件地执行stor proc

提问于
浏览
0

在我的Spring Batch Application中,我正在阅读,处理然后尝试使用 stored procedure 将ItemWriter写入数据库:

下面是我的CSV文件的样子,让我们说出我想要阅读,处理和写入的内容:

Cob Date;Customer Code;Identifer1;Identifier2;Price
20180123;ABC LTD;BFSTACK;1231.CZ;102.00

我的 ItemWriter

@Slf4j
public class MyDBWriter implements ItemWriter<Entity> {

    private final EntityDAO scpDao;

    public MyWriter(EntityDAO scpDao) {
        this.scpDao = scpDao;
    }

    @Override
    public void write(List<? extends Entity> items) {
        items.forEach(scpDao::insertData);
    }
}

我的DAO实现:

@Repository
public class EntityDAOImpl implements EntityDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private SimpleJdbcCall simpleJdbcCall = null;


    @PostConstruct
    private void prepareStoredProcedure() { 
        simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate).withProcedureName("loadPrice");
        //declare params
    }

    @Override
    public void insertData(Entity scp) {

        Map<String, Object> inParams = new HashMap<>();

        inParams.put("Identifier1", scp.getIdentifier1());
        inParams.put("Identifier2", scp.getIdentifier1());
        inParams.put("ClosingPrice", scp.getClosingPrice());
        inParams.put("DownloadDate", scp.getDownloadDate());

        simpleJdbcCall.execute(inParams);
    }
}

我用于更新的存储过程如下:

ALTER PROCEDURE [dbo].[loadPrice]
@Identifier1 VARCHAR(50),
@Identifier1  VARCHAR(50),
@ClosingPrice decimal(28,4),
@DownloadDate datetime

AS
 SET NOCOUNT ON;

UPDATE p
SET ClosingPrice = @ClosingPrice,
from Prices p
join Instrument s on s.SecurityID = p.SecurityID
WHERE convert(date, @DownloadDate) = convert(date, DownloadDate)
    and s.Identifier1 = @Identifier1


if @@ROWCOUNT = 0
    INSERT INTO dbo.Prices
    (
        sec.SecurityID
        , ClosingPrice
        , DownloadDate
    )
    select sec.SecurityID
        , @ClosingPrice
        , LEFT(CONVERT(VARCHAR, @DownloadDate, 112), 8)
    from dbo.Instrument sec
    WHERE sec.Identifier1 = @Identifier1

给我这个设置,我的要求之一是,如果我无法使用_750085更新/插入数据库,即没有 SecurityIDIdentifier1 匹配,我需要使用 Identifier2 更新/插入 . 如果你愿意,二级匹配 .

我怎么能在我的DAO insertData() 中这样做?它是业务逻辑,更喜欢java代码而不是存储过程,但我很想看看你的例子如何实现这一点 .

如何返回更新/插入行的结果并决定是否使用第二个标识符更新/插入?

1 回答

  • 0

    对于更新,我会将where子句更改为

    WHERE convert(date, @DownloadDate) = convert(date, DownloadDate)
    and (s.Identifier1 = @Identifier1 OR s.Identifier2 = @Identifier2)
    

    并为插入

    WHERE sec.Identifier1 = @Identifier1 OR sec.Identifier2 = @Identifier2
    

    即使我自己没有验证它,这应该工作 . 我假设identifier1和identifier2的给定值不能匹配Instrument表中的两个不同的行 .

相关问题