/**
* HQL查询的一个例子
*/
public static void hql()
{
Session s = null;
try
{
s = HibernateUtil.getSeesion();
//final String hql = "from User as u where u.name=?";
final String hql = "from User as u where u.name=:name";
final Query query = s.createQuery(hql);
//query.setString(0, "北京市"); //从0开始
query.setString("name", "北京市");
final List list = query.list();
for (final User u : list)
{
System.out.println(u.getName());
}
}
finally
{
if (s != null)
{
s.close();
}
}
System.out.println("HQL完成");
}
HibernateUtil工具类
package dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 这是一个工具类, 快速取得session
*
*/
public class HibernateUtil
{
static SessionFactory sessionFactory = null;
static
{
final Configuration cfg = new Configuration();
cfg.configure(); //路径可以改变
sessionFactory = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
/**
* 取得session
*
* @return session
*/
public static Session getSeesion()
{
return sessionFactory.openSession();
}
}
/**
* HQL 分页查询
*/
public static void page()
{
Session s = null;
try
{
s = HibernateUtil.getSeesion();
final String hql = " from User "; //User是类名
final Query q = s.createQuery(hql);
q.setFirstResult(0); //从第0条开始
q.setMaxResults(10); //取出10条
final List list = q.list();
for (final User u : list)
{
System.out.println(u.getId() + " " + u.getName());
}
}
finally
{
s.clear();
}
}
分享到:
2009-02-28 10:30
浏览 10598
评论
1 楼
zzjess
2016-08-09
赞