开发者

Java Query and Enum

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 开发者_C百科one SQL Query.


The only way out for me, is to use such 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 "
);
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()));;
}

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜