Hibernate查询方式示例


Hibernate查询方式
1、Query执行Hql语句

1)查询所有记录
Query query = session.createQuery("from Customer");
List list = query.list();
System.Out.println(list);

2)条件查询
Query query = session.createQuery("from Customer where name=?");
query.setString(0,"张三");
List list = query.list();
System.Out.println(list);

3)条件查询
Query query = session.createQuery("from Customer where name = ? and age = ?");
query.setString("aaa","张三");
query.setString("bbb","38");
System.Out.println(list);

4)分页查询
Query query = session.createQuery("from Customer");
query.setFirstResult(3);
query.setMaxResults(3);
List list = query.list();
System.Out.println(list);

Criteria
1)查询所有记录
Criteria criteria = session.createCriteria(Customer.class);
List list = criteria.list();
System.Out.println(list);

2)条件查询
Criteria criteria = session.createCriteria(Customer.class);
criteria.add(Restriction.eq("name","李健"));
List list = criteria.list();
System.Out.println(list);

3)条件查询
Criteria criteria = session.createCriteria(Customer.class);
criteria.add(Restriction.eq("name","李健"));
criteria.add(Restriction.eq("age",16));
System.Out.println(list);

4)分页查询
Criteria criteria = session.createCriteria(Customer.class);
criteria.setFirstResult(3);
criteria.setMaxResult(3);
System.Out.println(list);

3、SQLQuery

1)基本查询

SQLQuery sqlQuery = session.createSQLQuery(“select * from cst_customer”);

List list = sqlQuery.list();

for(Object[] objects : list){

System.Out.println(objects)

}

SQLQuery sqlQuery = session.createSQlQuery("select * from cst_customer");

sqlQuery.addEntity(Customer.class);

List list = sqlQuery.list();

for(Customer custoemr : list){

System.Out.println(customer);

}

你可能感兴趣的:(java)