'spring data jpa on timestamp field for current date?

I have to query on timestamp field for current date and get only 1 record. I can write the query like:

@Query("Select i From Log i Where i.createdBy = :userId And DATE(i.createdDate) = CURRENT_DATE")

JPA Entity:

@Entity
@Table(name = "log")
public class Log {

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

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

    @Column(name = "created_date", updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "yyyy-MM-dd HH:mm:ss")
    private Calendar createdDate;

    //SETTERS AND GETTERS
}   

TABLE:

CREATE TABLE `log` (
    `log_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `address` VARCHAR(30) NOT NULL,
    `created_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`log_id`)
)
ENGINE=InnoDB
;

here i am not able to limit the records, I know we can limit the records by sending Pageable, but again i have to get the record from list.

Is there any way to do this ? how can we do it in spring data jpa method name ?



Solution 1:[1]

You can use a Spring Data repository to do this like the following:

public interface LogRepository extends JpaRepository<Log, Long> {

  // just get one or null
  Log findOneByCreatedByAndCreatedDate(Instant createdBy, Instant createdDate);

  // get all, but pagable
  List<Log> findAllByCreatedByAndCreatedDate(Instant createdBy, Instant createdDate, Pageable pageable);

}

I assume you use Instant as timestamp, but this should also work for the other Java 8 date types or the old Date class.

Within your business logic you can now call:

Log log = logRepository.findOneByCreatedByAndCreatedDate(YOUR_TIMESTAMP, Instant.now());

// or
Log allLogs = logRepository.findOneByCreatedByAndCreatedDate(YOUR_TIMESTAMP, Instant.now(), PageRequest.of(0, 50));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rieckpil