1.HQL是Hibernate查询语言
21.基本查询:
select from 属性名 from 类名 where 属性名
//方法一:list()查询
session = sessionFactory.openSession();
String hql
Query query HQL session.create.createQuery(hql);
List<Emp> empList = query.list();
//eg:
public class TestHQL {
@Test
public void testBase(){
Session session = null;
try {
session = util.getSession();
//编写hql语句
String hql= "from Student";
//获取query对象
Query query = session.createQuery(hql);
//得到集合
List<Student> stulist = query.list();
//遍历集合
for(Student stu : stulist){
System.out.println("sname:"+stu.getSname());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
util.close(session);
}
}
}
//方法二:Iterate()查询
session= sessionFactory.openSession();
String hql = "from Emp";
Query query = session.createQuery(hql);
Iterator<Emp> empIterator = query.iterate();
//eg:
@Test
public void testIterate(){
Session session = null;
try {
session = util.getSession();
//编写hql语句
String hql= "from Student";
//获取query对象
Query query = session.createQuery(hql);
Iterator<Student> its = query.iterate();
while(its.hasNext()){
Student stu = its.next();
System.out.println("sname:"+stu.getSname());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
util.close(session);
}
}
21.基本查询:
select from 属性名 from 类名 where 属性名
//方法一:list()查询
session = sessionFactory.openSession();
String hql
Query query HQL session.create.createQuery(hql);
List<Emp> empList = query.list();
//eg:
public class TestHQL {
@Test
public void testBase(){
Session session = null;
try {
session = util.getSession();
//编写hql语句
String hql= "from Student";
//获取query对象
Query query = session.createQuery(hql);
//得到集合
List<Student> stulist = query.list();
//遍历集合
for(Student stu : stulist){
System.out.println("sname:"+stu.getSname());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
util.close(session);
}
}
}
//方法二:Iterate()查询
session= sessionFactory.openSession();
String hql = "from Emp";
Query query = session.createQuery(hql);
Iterator<Emp> empIterator = query.iterate();
//eg:
@Test
public void testIterate(){
Session session = null;
try {
session = util.getSession();
//编写hql语句
String hql= "from Student";
//获取query对象
Query query = session.createQuery(hql);
Iterator<Student> its = query.iterate();
while(its.hasNext()){
Student stu = its.next();
System.out.println("sname:"+stu.getSname());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
util.close(session);
}
}
区别:list方法比较方便,而iterate方法每查询一次需要执行一次sql语句
3.带参查询:
3.1基于参数位置的查询
--位置索引从0开始,不同于ps对象(从1开始)
eg:List<Student> list = session.createQuery(hql)
.setParameter(0,"杨戬")
.list();
3.2基于参数的名称查询
--[:参数名]
eg:List<Student> list = session.createQuery(hql)
.setParameter("n","杨戬")
.setParameter("a",23)
.list();