Java 如何在单个数据库调用中进行删除和选择?
我正在开发todo应用程序。我的删除映射如下所示:Java 如何在单个数据库调用中进行删除和选择?,java,spring-boot,jdbc,jdbctemplate,Java,Spring Boot,Jdbc,Jdbctemplate,我正在开发todo应用程序。我的删除映射如下所示: @DeleteMapping("/remove-todo") public ResponseEntity<?> removeTodo(@RequestParam("todo_id") String id, Authentication authentication) { SecurityUser user = (SecurityUser) authentication.
@DeleteMapping("/remove-todo")
public ResponseEntity<?> removeTodo(@RequestParam("todo_id") String id, Authentication authentication) {
SecurityUser user = (SecurityUser) authentication.getPrincipal();
todoDAO.deleteTodo(id, user.getUserId())
List<Todo> todos = todoDAO.getTodosByUserId(user.getUserId());
return todos;
}
@DeleteMapping(“/remove todo”)
public ResponseEntity removeTodo(@RequestParam(“todo_id”)字符串id,身份验证){
SecurityUser用户=(SecurityUser)身份验证。getPrincipal();
todoDAO.deleteTodo(id,user.getUserId())
List todos=todoDAO.getTodosByUserId(user.getUserId());
返回待办事项;
}
deleteTodo和GetToDosBySerid
@Override
public Todo deleteTodo(String id, String userId) {
String sql = "delete from todo where id = ? and userId = ? returning *";
try {
return jdbcTemplate.queryForObject(sql, new Object[]{id, userId}, new TodoMapper());
}catch (EmptyResultDataAccessException e){
System.out.println("NO ResultSet Found");
return null;
}
}
@Override
public List<Todo> getTodosByUserId(String userId) {
return jdbcTemplate.query("select * from todo where userId = ?",
new TodoMapper(), userId);
}
@覆盖
公共Todo deleteTodo(字符串id、字符串用户id){
String sql=“delete from todo,其中id=?和userId=?returning*”;
试一试{
返回jdbcTemplate.queryForObject(sql,新对象[]{id,userId},新TodoMapper());
}捕获(EmptyResultDataAccessE异常){
System.out.println(“未找到结果集”);
返回null;
}
}
@凌驾
公共列表getTodosByUserId(字符串用户ID){
返回jdbcTemplate.query(“从todo中选择*其中userId=?”,
新的TodoMapper(),userId);
}
我正在进行两次数据库调用,首先是删除todo,然后选择所有用户todo。
如何将这两种方法组合到单个查询中?我可以用batchUpdate完成吗?您可以将
delete
和list
方法组合成一个方法<代码>jdbcTemplate.update方法建议用于插入、更新和删除
public List<Todo> deleteTodo(String id, String userId) {
String sql = "delete from todo where id = ? and userId = ?";
try {
if (jdbcTemplate.update(sql, new Object[]{id, userId}, new TodoMapper()) == 1) {
return jdbcTemplate.query("select * from todo where userId = ?",
new TodoMapper(), userId);
}
} catch (EmptyResultDataAccessException e){
System.out.println("NO ResultSet Found");
return new ArrayList<>();
}
}
公共列表deleteTodo(字符串id,字符串用户id){
String sql=“从todo中删除,其中id=?和userId=?”;
试一试{
if(jdbcTemplate.update(sql,新对象[]{id,userId},新TodoMapper())==1){
返回jdbcTemplate.query(“从todo中选择*其中userId=?”,
新的TodoMapper(),userId);
}
}捕获(EmptyResultDataAccessE异常){
System.out.println(“未找到结果集”);
返回新的ArrayList();
}
}
这样做有什么好处吗?是的,因为我会在更新后选择并创建。您不太可能这样做。删除特定记录然后返回其他记录是两种不同的操作,应该分别执行。此外,批处理执行不用于选择记录。