Get random object from SQL database via Hibernate

和自甴很熟 提交于 2020-01-04 04:59:06

问题


I have following MySql dependent code ( ORDER BY RAND() ) . I would like to know if there is hibernate HQL alternative for it (admin is boolean tag indicating that the user as an admin). This is working code:

public long getRandomAdmin() {
    Session session = getSession();
    Query selectQuery = session.createSQLQuery("SELECT user_id FROM users WHERE admin = '1' ORDER BY RAND()");
    selectQuery.setMaxResults(1);

    List<BigInteger> list = null;
    try {
        list = selectQuery.list();
    } catch (HibernateException e) {
        log.error(e);
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }

    if (list.size() != 1) {
        log.debug("getRandomAdmin didn't find any user");
        return 0;
    }
    log.debug("found: " + list.get(0));

    return list.get(0).longValue();
}

回答1:


See this link: http://www.shredzone.de/cilla/page/53/how-to-fetch-a-random-entry-with-hibernate.html

Criterion restriction = yourRestrictions;
Object result = null;  // will later contain a random entity
Criteria crit = session.createCriteria(Picture.class);
crit.add(restriction);
crit.setProjection(Projections.rowCount());
int count = ((Number) crit.uniqueResult()).intValue();
if (0 != count) {
  int index = new Random().nextInt(count);
  crit = session.createCriteria(Picture.class);
  crit.add(restriction);
  result = crit.setFirstResult(index).setMaxResults(1).uniqueResult();
}

This is what you want. Keep Hibernate as an abstraction layer while still being able to query a random object. Performance suffers a bit, though.

Although I've been using Hibernate a lot, I don't know a more elegant way that is easy to use. Imho you should wrap that method behind a facade.



来源:https://stackoverflow.com/questions/4232934/get-random-object-from-sql-database-via-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!