如何用LocalDate查询LocalDateTime?

How to query LocalDateTime with LocalDate?

我有一个 class,其中包含一个 java.time.LocalDateTime 类型的属性。

public class MyClass{
    // ...
    private LocalDateTime fecha;
    // ...
}

我正在使用 Spring 数据存储库。我想要完成的是根据日期查询实体:

@Service
public interface IRepository extends CrudRepository<MyClass, UUID> {
    // ...
    public void deleteByFecha(LocalDate fecha);
    // ...
}

但这不起作用,因为会抛出异常:

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [2016-10-05] did not match expected type [java.time.LocalDateTime (n/a)];

所以问题是如何通过 fecha 但使用 LocalDate 在数据库中查询 MyClass?

编辑 为了以防万一有人遇到同样的问题,我想出了一个解决方案:修改存储库的方法,使其如下所示:

import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
// ...

@Service
public interface IRepository extends CrudRepository<MyClass, UUID> {

    @Transactional
    @Modifying
    @Query("DELETE FROM MyClass mtc WHERE YEAR(mtc.fecha)=?1 AND MONTH(mtc.fecha)=?2 AND DAY(mtc.fecha)=?3")
    public void deleteByFecha(Integer year, Integer month, Integer day);

}

试试这个(未测试):

public interface IRepository extends CrudRepository<MyClass, UUID> {
    // ...
    default void delByFecha(LocalDate fecha) {

        deleteByFechaBetween(fecha.atStartOfDay(), fecha.plusDays(1).atStartOfDay());

    }

    void deleteByFechaBetween(LocalDateTime from, LocalDateTime to);
    // ...
}

我知道这是一个老问题,但为了以后有同样问题的人可以使用这个解决方案:

 default void delByFecha(@RequestParam(name = "date") @DateTimeFormat(iso = ISO.DATE) LocalDate date)

效果很好!

Zombie Thread,但我想我会把我的解决方案扔进戒指。

我遇到了类似的问题,我最终使用了 Hibernate @Formula

例如:

class MyClass {

  private LocalDateTime fecha;

  /* fecha referenced within the annotation should be the column name. 
   * So, if it's different the Java field name (i.e. fecha_dtm or something), 
   * make sure to use it.
  */
  @Formula("CAST(fecha as DATE)") 
  private LocalDate fechaDate;

}

那么你的存储库:

public interface IRepository extends CrudRepository<MyClass, UUID> {
  deleteByFechaDate(LocalDate fecha); // note it's FechaDate, not Fetcha
}

尝试坚持使用符合 ANSI SQL 的函数(CAST 符合 SQL-92,因此被广泛接受)以保持数据库实现的一致性。但是,可以使用 DB 特定的函数,你只是失去了可移植性。

希望对您有所帮助!

我今天有一个 similar question(我正在制作 SELECT,而不是删除),在这里发布之后,我想出了两个解决方案:

@Query(value = "DELETE FROM MyClass mc WHERE DATE(fecha) =:fecha", nativeQuery = true)
public void deleteByFecha(LocalDate fecha);

或者,按照 Cepr0's ,我成功地测试了他的解决方案:

default void deleteByFecha(LocalDate fecha) {
    deleteByFechaBetween(fecha.atStartOfDay(), fecha.plusDays(1).atStartOfDay());

}

void deleteByFechaBetween(LocalDateTime from, LocalDateTime to);