【发布时间】:2021-08-06 12:12:09
【问题描述】:
我正在尝试在 Spring 上创建一个 todo 应用程序。它快完成了,但我遇到了一个问题。我需要按用户 ID 过滤待办事项并选择它们在给定日期之间。我在我的 TodoRepository 中为此创建了一个方法。但是当我将请求发送到 url 时,它给了我一个空数组。
这是存储库类:
除了我提到的那个之外,所有方法都可以正常工作。
@Repository
public interface TodoRepository extends JpaRepository<Todo, Long> {
List<Todo> findTodosByUserId(Long id);
List<Todo> findTodosByUserIdOrderByDateAsc(String id);
List<Todo> findAllByDateBetween(Date date, Date date2);
List<Todo> findTodosByDateBetweenAndUserId(Date date, Date date2, Long id);
}
这就是我在 TodoService 类中使用的方法:
@Service
public class TodosService {
@Autowired
TodoRepository todoRepository;
//other methods..
public List<Todo> filterTodosByUserId(FilterTodoByUserDto dto){
Date date1 = dto.getDate1();
Date date2 = dto.getDate2();
Long id = dto.getId();
return todoRepository.findTodosByDateBetweenAndUserId(date1, date2, id);
}
}
FilterTodoByUserDto 类:
public class FilterTodoByUserDto {
private Long id;
private Date date1;
private Date date2;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate1() {
return date1;
}
public void setDate1(Date date1) {
this.date1 = date1;
}
public Date getDate2() {
return date2;
}
public void setDate2(Date date2) {
this.date2 = date2;
}
@Override
public String toString() {
return "FilterTodoByUserDto{" +
"id=" + id +
", date1=" + date1 +
", date2=" + date2 +
'}';
}
}
最后,控制器类:
@RestController
@RequestMapping("/api")
public class TodoController {
@Autowired
private TodosService todosService;
//other methods..
@GetMapping("user/todos/filter")
public List<Todo> filterTodosById(@RequestBody FilterTodoByUserDto dto){
List<Todo> todos = todosService.filterTodosByUserId(dto);
return todos;
}
//other methods..
}
我用邮递员发送的请求正文:
{"userId":"1", "date1":"2021-01-01", "date2":"2000-01-01"}
数据库输出:
mysql> select * from todos;
+----+----------------------------+-------------+-------------+---------+
| id | date | description | todo_status | user_id |
+----+----------------------------+-------------+-------------+---------+
| 1 | 2012-12-12 00:00:00.000000 | deneme | TODO | 2 |
| 2 | 2010-10-10 00:00:00.000000 | deneme2 | TODO | 2 |
| 3 | 2010-01-01 00:00:00.000000 | deneme5 | DONE | 1 |
| 4 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 5 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 6 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 7 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 8 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 9 | 2010-01-01 00:00:00.000000 | deneme | DONE | 2 |
+----+----------------------------+-------------+-------------+---------+
9 rows in set (0,01 sec)
【问题讨论】:
-
datedate1date2看起来都非常相似 - 容易混淆,因此请仔细检查您的代码。此外,很少有日期大于 2021 年小于 2020 年。
标签: mysql spring api spring-security