简体   繁体   English

JdbcTemplate.update()插入返回值

[英]JdbcTemplate.update() insert return values

JdbcTemplate.update() returns number of rows affected - so you not only know that delete/update was sucessfull, you also know how many rows were deleted/updated. JdbcTemplate.update()返回受影响的行数 - 因此您不仅知道删除/更新是成功的,还知道删除/更新了多少行。

What will be the return value if I try to insert a row. 如果我尝试插入一行,返回值是多少。

Is it possible to get return value as "0"?? 是否有可能将返回值设为“0”?

 private static final String insertSql =
 "INSERT INTO employee (" +
 " name, " +
 " surname, " +
 " title, " +
 " created) " +
 "VALUES (John, Smith, Software developer, new Date())";
 int row = template.update(insertSql, params, types);

是的,理论上你应该得到0或1,但是如果没有插入行,那将是由于一个错误,所以会抛出一个DataAccessException ,这就是你怎么知道出错了什么并且没有创建行的方法。

To answer your question, yes, as @Turophile pointed out, you will get a 0 or 1 in response as you can tell from the method signature (which returns an int). 要回答你的问题,是的,正如@Turophile指出的那样,你可以从方法签名 (它返回一个int)中得到一个0或1的响应。

In response to @Turophile comment (sorry I can't add a comment :/ ), to avoid this and avoid partial data being saved to the database, use Springs Transaction Management (tx). 响应@Turophile 评论 (抱歉,我无法添加评论:/),为了避免这种情况并避免将部分数据保存到数据库,请使用Springs Transaction Management(tx)。 This would allow you to rollback transactions based on specific exceptions or all exceptions from the Exception class. 这将允许您基于特定异常或Exception类中的所有异常回滚事务。 Mind you, by default, @Rollback rolls back transactions for runtime, unchecked exceptions only . 请注意,默认情况下,@ Rollback 回滚运行时的事务, 检查未经检查的异常。

@Transactional(rollbackFor = Exception.class)
public Employee updateEmployee(Employee pEmployee) { ... }

The @Transactional can also be added to the class as well, but I would read up more on it if you are interested in implementing this feature. @Transactional也可以添加到类中,但如果您对实现此功能感兴趣,我会阅读更多内容 There is a lot of good documentation on tx. 关于tx有很多很好的文档。

As a side note, I don't recommend lying to the caller of your method. 作为旁注,我不建议对你的方法的来电者撒谎。 If you call a method that says "update", run a query that'll update the record, if you want to insert/create a new record, create or call a method that "inserts" a new record into your table -- inserting a duplicate record wouldn't work anyways if the primary key(s) are unique. 如果你调用一个说“更新”的方法,运行一个将更新记录的查询,如果你想插入/创建一个新记录,创建或调用一个方法将一个新的记录“插入”你的表 - 插入如果主键是唯一的,则重复记录无论如何都不会起作用。

jdbctemplate.update will return in integer format as we know. 我们知道jdbctemplate.update将以整数格式返回。 in order to find 0 or 1 just do this below simple code 为了找到0或1,只需在简单的代码下执行此操作

int i=jdbctemplate.update(.your db call..);

it will return 1 for success and 0 for failure case so, according to it you can process your logic. 它将返回1表示成功,0表示失败情况,因此,根据它,您可以处理您的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM