Spring Jdbc查询执行

问题描述:

有谁知道我可以使用Spring Jdbc模板方法来执行这个'upsert'还是另外一种方法来执行一次数据库调用中的操作?Spring Jdbc查询执行

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

完全相同的副本 - http://stackoverflow.com/questions/2104211/spring-jdbc-template-query-execution – 2010-01-20 19:23:35

+0

不留神发布两次,DUP已被删除 – 2010-01-20 20:20:49

原来我接近,但忘了一步。

我不得不更改查询本身:

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 

然后在我的道只需要使用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); } 
    } 
} 

不应该是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; 
+0

没有,存在位于不同的表上,本质上它检查主键上是否存在外键约束,从而避免了如果该ID不在“报表”表中的情况下导致外键冲突。 – 2010-01-20 21:27:56

+0

哦,错过了它是一个不同的表! – RedFilter 2010-01-20 21:34:09