Spring Boot API问题:按日期获取列表数据返回空白页
/transits/{date}路径无返回的问题 Hey there, let's figure out why your /transits/2017-10-22 endpoint is coming back empty while the list endpoint works perfectly. Here are the most likely culprits to check:
1. 先确认核心数据问题
First off, take a look at the sample data your list endpoint returns: all dates are 3917-11-21—that's a year way in the future, not 2017. Did you accidentally mess up date handling when saving records?
Try running a direct query against your database like:
SELECT * FROM transits WHERE date = '2017-10-22';
If there are no results here, that's why your API returns nothing. You'll need to fix the data insertion logic to store dates correctly (like making sure you're not shifting the year by 2000 or something).
2. 检查路径变量的参数绑定
If your database does have 2017-10-22 data, check how your controller method is receiving the date parameter:
- If you're using
LocalDate(recommended for date handling), you need to explicitly specify the date format so Spring can parse the path variable correctly:@GetMapping("/transits/{date}") public List<Transit> getTransitsByDate( @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date ) { // Your query logic here } - Without the
@DateTimeFormatannotation, Spring might fail to convert the string"2017-10-22"to aLocalDate, leading to either an unhandled exception (which would usually return an error, not blank) or a malformed date that doesn't match any records.
3. 验证查询逻辑正确性
Double-check your repository query method to make sure it's filtering correctly:
- For JPA repositories, if you're using a custom query:
Ensure the field name (@Query("SELECT t FROM Transit t WHERE t.date = :targetDate") List<Transit> findByDate(@Param("targetDate") LocalDate date);t.date) matches exactly with thedatefield in yourTransitentity class. Typos here will result in no matches. - If you're using Spring Data's derived queries (like
List<Transit> findByDate(LocalDate date);), make sure the method name follows Spring Data conventions correctly.
4. 加日志调试定位问题
Add some logging to your controller method to see exactly what's happening:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RestController @RequestMapping("/transits") public class TransitController { private static final Logger log = LoggerFactory.getLogger(TransitController.class); // ... autowire repository @GetMapping("/{date}") public List<Transit> getTransitsByDate( @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date ) { log.info("Received request for date: {}", date); List<Transit> results = transitRepository.findByDate(date); log.info("Found {} transit records for date {}", results.size(), date); return results; } }
Check your application logs after hitting the endpoint:
- If the date logged is not
2017-10-22, your parameter binding is broken. - If the result count is 0, either there's no data for that date or your query is wrong.
内容的提问来源于stack exchange,提问作者D.Skowron

