簡體   English   中英

Spring Batch有條件地執行stor proc

[英]Spring batch executing stor proc conditionally

在我的Spring Batch應用程序中,我正在讀取,處理,然后嘗試使用ItemWriter使用stored procedure將其寫入數據庫:

以下是我的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

給我進行此設置,我的要求之一就是,如果我無法使用@Identifier1更新/插入數據庫,即沒有與Identifier1匹配的SecurityID ,則需要使用Identifier2更新/插入。 如果您願意,可以進行二級比賽。

如何在我的DAO insertData()執行此操作? 它是業務邏輯,並且更喜歡使用Java代碼而不是存儲的proc,但是我很想看看您的示例如何實現這一點。

如何返回行被更新/插入的結果並決定是否使用第二個標識符進行更新/插入?

對於更新,我將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表中的兩個不同行匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM