gpt4 book ai didi

java - JPQL:为什么我无法按日期选择记录?

转载 作者:行者123 更新时间:2023-11-30 03:47:21 25 4
gpt4 key购买 nike

我正在使用 JPA 2.1、eclipseLink 和 SQLite3 数据库制作一个应用程序。

我有一个客户表,其中我以毫秒为单位保存客户的生日。

在实体客户端中,我使用转换器将生日值从 DateTime (JodaTime) 转换为 Long:

@Converter
public class DateTimeConverter implements AttributeConverter<DateTime, Long> {

@Override
public Long convertToDatabaseColumn(DateTime arg0) {
return arg0 == null ? null : ((DateTime) arg0).getMillis();
}

@Override
public DateTime convertToEntityAttribute(Long arg0) {
return arg0 == null ? null : new DateTime(arg0);
}
}

我试图在 JPQL 中按出生日期获取其中一位客户,但我不知道该怎么做。我尝试了几件事,但没有一个能正常工作。例如,我尝试这样做:

EntityClient client = new EntityClient();
client.setBirthDate(new DateTime("1966-07-21"));

ArrayList<EntityClient> clientsByBirthdate = new ArrayList<>();

String query = "SELECT o FROM " + EntityClient.class.getCanonicalName() + " o " +
"WHERE o.birthDate = " + client.getBirthDate().getMillis();

for(Object obj : entityManager.createQuery(query).getResultList())
clientsByBirthdate.add(EntityClient.class.cast(obj));

但它不是检索正确的记录,而是检索出生日期设置为 null 的所有记录。

我做错了什么?

最佳答案

切勿使用字符串连接将参数传递给查询。使用参数:

String query = "SELECT o FROM EntityClient o " + 
"WHERE o.birthDate = :birthDate";
List<EntityClient> list =
entityManager.createQuery(query, EntityClient.class)
.setParameter("birthDate", new DateTime("1966-07-21"))
.getResultList()

关于java - JPQL:为什么我无法按日期选择记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25309388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com