【问题标题】:Spring Jdbc query executionSpring Jdbc 查询执行
【发布时间】:2010-01-20 19:16:55
【问题描述】:

有谁知道我可以使用什么 Spring Jdbc 模板方法来执行这个“upsert”或另一种也可以在一个数据库调用中执行操作的替代方法?

UPDATE jasper_report SET Uri = 'update' WHERE ReportId = 99;
IF @@ROWCOUNT = 0 AND Exists(Select 1 FROM report Where Id = 99)
BEGIN   
    INSERT INTO jasper_report  (ReportId, Uri) VALUES (99, 'insert') 
END;

【问题讨论】:

标签: sql sql-server spring jdbc spring-jdbc


【解决方案1】:

原来我很接近但忘记了一步。

我不得不将查询本身更改为:

BEGIN 
  UPDATE jasper_report SET Uri = ? WHERE ReportId = ? 
  IF @@ROWCOUNT = 0 AND EXISTS(SELECT 1 FROM report WHERE Id = ?) 
  BEGIN 
       INSERT INTO jasper_report  (ReportId, Uri) VALUES (?, ?) 
  END 
END

那么在我的Dao中只需要使用Spring's JdbcTemplate update method。它看起来像这样:

@Repository("jasperReportsDao")
public class JasperReportsDaoImpl extends JdbcTemplate implements JasperReportsDao {

    @Override
    public void saveJasperReport(JasperReport report) {
        // If a record already exists, do an update, otherwise, do an insert
        int rowsAffected = this.update(UPSERT_JASPER_REPORT, new Object[] { report.getUri(), report.getId(),
                               report.getId(), report.getId(), report.getUri()} );

        if(log.isDebugEnabled()) { log.debug("Rows affected: " + rowsAffected); }
    }
}

【讨论】:

    【解决方案2】:

    不应该是Not Exists吗?

    无论如何,我认为没有Not Exists 也可以正常工作,因为@@ROWCOUNT 已经为您提供了该信息:

    UPDATE jasper_report SET Uri = 'update' WHERE ReportId = 99;
    IF @@ROWCOUNT = 0 
    BEGIN   
        INSERT INTO jasper_report (ReportId, Uri) VALUES (99, 'insert') 
    END;
    

    【讨论】:

    • 不,exists 在不同的表上,本质上是检查主表上是否存在外键约束,从而避免在 id 不在“报告”表中时违反外键.
    • 哦,错过了这是一张不同的桌子!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多