Java 查询和枚举
我在从查询获取结果列表时遇到问题。查询返回一个空对象。我不知道为什么会发生。但是如果我评论它的 WHERE 语句它工作正常,但是我有两个可以指定结果的枚举。我不认为我是第一个使用它的人,除了使用 NamedQuery 之外,谷歌没有给出任何答案。这是我的代码:
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public DeviceProfileAttribute getRandomDeviceProfileAttribute(Category category, Platform platform) {
Query q = em.createQuery("SELECT d FROM DeviceProfileAttribute d " +
"WHERE d.tenantAttribute.attribute.category=:category AND " +
"d.tenantAttribute.attribute.platform=:platform " +
"ORDER BY RAND()");
q.setParameter("category", category);
q.setParameter("platform", platform);
q.setMaxResults(1);
if (q.getResultList().isEmpty()) {
return null;
} else {
return (DeviceProfileAttribute) q.getResultList().get(0);
}
}
我确信 null 不仅仅是一个答案。
提前致谢。
PS 现在可能有人在输入所有参数后检查此查询吗?
PPS 问题在于在一个 SQL 查询中使用 Enum 和 ORDER by RAND() 。
I have a problem this getting result list from query. Query return me an null Object. I dont have any idea why its happen. But if I comment its WHERE statement its work fine, but i have two Enum that can specify the result. I dosent think that Im first with it, and google didnt give any answer except to use NamedQuery. This is my code :
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public DeviceProfileAttribute getRandomDeviceProfileAttribute(Category category, Platform platform) {
Query q = em.createQuery("SELECT d FROM DeviceProfileAttribute d " +
"WHERE d.tenantAttribute.attribute.category=:category AND " +
"d.tenantAttribute.attribute.platform=:platform " +
"ORDER BY RAND()");
q.setParameter("category", category);
q.setParameter("platform", platform);
q.setMaxResults(1);
if (q.getResultList().isEmpty()) {
return null;
} else {
return (DeviceProfileAttribute) q.getResultList().get(0);
}
}
Im sure that null isnt only one answer.
Thanks in advance.
P.S May be somebody now to check this query after puting all parameters ?
P.P.S The problem is in using Enum and ORDER by RAND() in one SQL Query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对我来说唯一的出路是使用这样的代码:
The only way out for me, is to use such code :