2011-07-29 67 views
0

我有一个问题,这个查询结果列表。查询返回一个空对象。我不知道为什么会发生。但如果我评论它的WHERE语句它的工作正常,但我有两个枚举可以指定结果。我dosent认为我首先与它,谷歌没有给出任何答案,除了使用NamedQuery。这是我的代码:Java查询和枚举

@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不是只有一个答案。

在此先感谢。

P.S现在可能有人在放置所有参数后检查此查询吗?

P.P.S问题是在一个SQL查询中使用Enum和ORDER by RAND()。

+1

“选择d”是不是有效的SQL。您无法从表名中选择表名。 –

+0

但它不会给出任何错误,我认为如果它,它会给某种例外。 – e8kor

+3

@Paul:'SELECT d'是有效的JPQL。 –

回答

0

出来对我来说,唯一的办法,就是用这样的代码:

@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 " 
); 
q.setParameter("category", category); 
q.setParameter("platform", platform); 
if (q.getResultList().isEmpty()) { 
    return null; 
} else { 
    return (DeviceProfileAttribute) q.getResultList().get(new Random().nextInt(q.getResultList().size()));; 
} 

}