How to query LocalDateTime with LocalDate?

后端 未结 5 1183
一向
一向 2021-01-22 02:49

I\'ve got a class which contains an atttribute of java.time.LocalDateTime type.

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


        
相关标签:
5条回答
  • 2021-01-22 02:50

    Zombie Thread, but thought I'd throw my solution into the ring.

    I had a similar issue, I ended up using a Hibernate @Formula

    For example:

    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;
    
    }
    

    Then your repository:

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

    Try to stick to ANSI SQL compliant functions (CAST is SQL-92 compliant, so pretty widely accepted) to keep things consistent across database implementations. However, DB specific functions can be used, you'll just lose portability.

    Hopefully this helps you!

    0 讨论(0)
  • 2021-01-22 02:51

    I had a similar question today (I was making SELECT, not a DELETE) and after posting it on here, I came up with two solutions:

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

    Alternatively, following Cepr0's answer, I tested with success his solution:

    default void deleteByFecha(LocalDate fecha) {
        deleteByFechaBetween(fecha.atStartOfDay(), fecha.plusDays(1).atStartOfDay());
    
    }
    
    void deleteByFechaBetween(LocalDateTime from, LocalDateTime to);
    
    0 讨论(0)
  • 2021-01-22 03:06

    LocalDateTime and LocalDate are incompatible types as is (although they both implement Temporal, in case you can work with that).

    Otherwise, you have a LocalDateTime#toLocalDate conversion method available.

    0 讨论(0)
  • 2021-01-22 03:07

    Try this (not tested):

    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);
        // ...
    }
    
    0 讨论(0)
  • 2021-01-22 03:07

    I know that this one is a old issue, but for the future, who is with the same problem can use this solution:

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

    It's works perfectly!

    0 讨论(0)
提交回复
热议问题