Java 两个日期之间的jpa查询
这是我对SQL Server的查询:Java 两个日期之间的jpa查询,java,spring,jpa,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 " + "WHE
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);
并收到此错误:
查询方法public abstract java.lang.Long.com.finance.biblioteca.repository.nolegiorepository.CountByUteneId和libroid(java.lang.Long,java.lang.Long,java.time.LocalDate,java.time.LocalDate)时验证失败
您需要使用两种方法实现
AttributeConverter
接口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();
}
}
import java.sql.Date;
导入java.time.LocalDate;
@转换器(自动应用=真)
公共类LocalDateAttributeConverter实现AttributeConverter{
@凌驾
public Date convertToDatabaseColumn(LocalDate locDate){
return locDate==null?null:Date.valueOf(locDate);
}
@凌驾
公共LocalDate convertToEntityAttribute(日期sqlDate){
返回sqlDate==null?null:sqlDate.toLocalDate();
}
}
有关详细信息,请参阅此链接。我对您的问题的看法是,您没有用于
之间的的参数。您只将字段作为名称而不是参数。
您的代码应该如下所示:
@Query(value = "SELECT COUNT(n) from Noleggio n " +
"WHERE n.libroId = ?1 AND n.utenteId=?2 AND CURRENT_DATE() BETWEEN ?3 AND ?4")
Long countByUtenteIdAndLibroId(Long idLibro, Long idUtente, LocalDate inizioPrestito, LocalDate finePrestito);
根据您的JPA版本,您需要或不需要按照上面的回答编写自己的JPA。您尝试的方法不起作用?不,它不起作用。您是否收到一些错误?没有结果?告诉我们发生了什么。方法公共抽象java.lang.Long com.finance.biblioteca.repository.nolegiorepository的查询验证失败。CountByUteneTiendLibroid(java.lang.Long、java.lang.Long、java.time.LocalDate、java.time.LocalDate)!从noleggi中选择*,其中id_utente=1、id_libro=25和GETDATE()在INGISIO_prestito和fine_prestito之间,如果我的当前日期在数据库中的两个日期之间,则我的查询必须计数,该数据库引用了具有特定bookIDi的用户ID。我尝试了@query(value=“SELECT count(n))来自Noleggio n,其中idutente=:idutente和idlibro=:idlibro和:n.initialioprestito和n.finepresito之间的数据)长countbynoleggioute和libroid(@Param(“idutete”)长idute,@Param(“idlibro”)Long IdLibro,@Param(“data”)LocalDate data);错误为:com.microsoft.sqlserver.jdbc.SQLServerException:列名“idutete”无效。现在我更清楚了。此错误意味着表中没有名为idute
的列。请检查名称并根据需要更正。