两个日期之间的jpa查询

时间:2019-12-27 14:47:55

标签: java spring jpa

这是我在SQL Server上的查询

select count(*) from noleggi 
where id_utente = 1 AND id_libro =25 and GETDATE() BETWEEN inizio_prestito AND fine_prestito

使用jpa信息库的正确语法是什么?

我尝试过:

@Query(value = "SELECT COUNT(n) from Noleggio n " +
            "WHERE  n.libroId = ?1 AND n.utenteId=?2 AND CURRENT_DATE() BETWEEN n.inizioPrestito AND n.finePrestito")

    Long countByUtenteIdAndLibroId(Long idLibro, Long idUtente, LocalDate inizioPrestito, LocalDate finePrestito);

2 个答案:

答案 0 :(得分:0)

您需要使用其两个方法AttributeConverter<LocalDate, Date>convertToDatabaseColumn实现convertToEntityAttribute接口。

import java.sql.Date;
import java.time.LocalDate;

@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
        return locDate == null ? null : Date.valueOf(locDate);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
        return sqlDate == null ? null : sqlDate.toLocalDate();
    }
}

请参阅此链接以获取更多详细信息。 https://thoughts-on-java.org/persist-localdate-localdatetime-jpa/

答案 1 :(得分:0)

我对您的问题的看法是您没有screenTarget的参数。您只是将字段作为名称而不是indexed参数。 您的代码应如下所示:

BETWEEN

取决于您的JPA版本,您将需要或不需要编写自己的LocalDateConverter,如上面的响应所述。