Hibernate5:HQL查询

1. 基本查询

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction()

String hql = "from Customer";

Query query = session.createQuery(hql);

List list = query.list();

System.out.println(list);

tx.commit();

session.close();

2. 条件查询

2.1 基本条件查询

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

//查询出唯一一个结果

String hql = "from Customer where cust_id = 1";

Query query = session.createQuery(hql);

Customer customer = (Customer) query.uniqueResult();

System.out.println(customer);

tx.commit();

session.close();

2.2 问号占位符查询

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

//问号占位符

String hql = "from Customer where cust_id = ?";

Query query = session.createQuery(hql);

query.setParameter(0, 2l);

Customer customer = (Customer) query.uniqueResult();

System.out.println(customer);

tx.commit();

session.close();

2.3. 命名占位符查询

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

//命名占位符

String hql = "from Customer where cust_id = :cust_id";

Query query = session.createQuery(hql);

query.setParameter("cust_id", 2l);

Customer customer = (Customer) query.uniqueResult();

System.out.println(customer);

tx.commit();

session.close();

3. 分页查询

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

//分页查询

String hql = "from Customer";

Query query = session.createQuery(hql);

//相当于limit ?,?中的两个问号

query.setFirstResult(4);

query.setMaxResults(2);

List list = query.list();

System.out.println(list);

tx.commit();

session.close();

 

你可能感兴趣的:(hibernate)