首页 > 解决方案 > 无法将“java.lang.String”转换为“java.time.LocalDateTime”(Spring)

问题描述

我无法让这个小应用程序在 Spring Boot 中工作。其中包括将所有已在两个日期之间注册的“客户”。

实体

@Entity
@Setter
@Getter
@Table(name = "clients")
public class Client implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name

    @Column(name = "surname")
    private String surname;

    @Column(name = "registration_date")
    private LocalDateTime registrationDate

}

存储库:

@Query(value = "SELECT * FROM clients WHERE registration_date >= :from AND 
registration_date <= :to", nativeQuery = true)
List<Cliente> findRegisteredClients(LocalDateTime from, LocalDateTime to);

服务:

@Transactional public List findRegisteredClients(LocalDateTime from, LocalDateTime to) throws Exception { try { return clientRepository.findRegisteredClients(from, to); } catch (Exception e) { throw new Exception(e.getMessage()); }

控制器:

@

GetMapping("/findClients/{from}/{to}")
    public ResponseEntity<?> getRegisteredClients(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime from,
                                                    @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime to) {
        try {
            return ResponseEntity.status(HttpStatus.OK).body(clientService.findRegisteredClients(from, to));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("{\"message\": \"Error. Please try again later.\"}");
        }
    }

这些是我迄今为止在我的数据库中的记录(使用 MySql):

我在 Postman 中尝试的端点如下:

http://localhost:9000/api/v1/clients/findClients/2021-06-03/2021-06-03

运行它给我带来了这个问题标题的错误。我肯定犯了一个非常严重的错误。

澄清:我正在使用 LocalDateTime 处理实体“客户端”,因为那时我必须处理从日志中获得的小时和分钟。

提前感谢您的任何帮助!

标签: springspring-bootspring-data-jpa

解决方案


使用 java Date parser 解析存储日期的字符串。

字符串 sDate1="03/06/2021";
//注意这里的格式

日期 date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1); System.out.println(sDate1+"\t"+date1);

您可以参考https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html


推荐阅读