Spring Jdbc query execution

两盒软妹~` 提交于 2020-01-06 03:18:22

问题


Does anyone know how what Spring Jdbc template method I could use to execute this 'upsert' or an alternative approach that would also perform the operations in one database call?

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;

回答1:


Turns out I was close but forget a step.

I had to change the query itself to:

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

Then in my Dao only needed to use Spring's JdbcTemplate update method. It looks something like this:

@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:


Shouldn't that be Not Exists?

At any rate I think it would work fine without the Not Exists, since @@ROWCOUNT is already giving you that info:

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


来源:https://stackoverflow.com/questions/2104206/spring-jdbc-query-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!