---
title: "hibernate 随机 查询"
author: "conkeyn"
date: "2009-04-03T21:36:29Z"
tags: ["Hibernate"]
slug: "hibernate"
draft: false
lastmod: "2009-04-23T19:16:04Z"
id: 361227
url: "https://conkeyn.iteye.com/blog/361227"
---

```
/**
	 * 随机取出N条记录
	 * 
	 * @param filetype
	 * @param position
	 * @param dialog_box_type
	 * @param total
	 *            记录总数
	 * @param count
	 *            要取出几条
	 * @return
	 */
	@Override
	public List<Adv> getAdvs(String filetype, String position,
			String dialog_box_type, int total, int count) {
		String hql = "from Adv as adv where adv.id is not null ";
		if (StringUtils.isNotBlank(filetype)) {
			hql += " and adv.filetype ='" + filetype + "' ";
		}
		if (StringUtils.isNotBlank(position)) {
			hql += " and adv.position ='" + position + "' ";
		}
		if (StringUtils.isNotBlank(dialog_box_type)) {
			hql += " and adv.type.id ='" + dialog_box_type + "' ";
		}
		int first = total - count;
		first = first >= 0 ? first : 0;
		first = (int) Math.floor(Math.random() * first);
		return getSession().createQuery(hql).setFirstResult(first)
				.setMaxResults(count).list();
	}
```