第十七章 离线,命名查询

?
离线查询
在Hibernate中,查询有两种方式,一种是HQL, 另一种是对象方式查询: Criteria
我们知道在使用对象方式查询时, Criteria对象需要通过Query对象来构造,Query又需要通过Session来获取,那么这时我们一般会在Dao层中写好对象查询的方法.
添加Service层:
接口:
public interface StudentService {
public List<Student> findByProperty(Student student) throws Exception;
}
实现类:
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
public StudentServiceImpl() {
studentDao = new StudentDao();
}
@Override
public List<Student> findByProperty(Student student) throws Exception {
DetachedCriteria query = DetachedCriteria.forClass(Student.class);
if (student.getName() != null) {
query.add(Restrictions.like("name", "%" + student.getName() + "%"));
}
//调用Dao层的方法来进行实际查询
return studentDao.findByProperty(query);
}
}
Dao层添加一个方法:
public List<Student> findByProperty(DetachedCriteria query) throws Exception {
Session session = null;
Transaction transaction = null;
List<Student> list = new ArrayList<Student>();
try {
session = HibernateUtil.getSession();
transaction = session.getTransaction();
transaction.begin();
list = query.getExecutableCriteria(session).list();
transaction.commit();
} catch (Exception e) {
transaction.rollback();
throw e;
}
return list;
}
需要注意这一句代码:
list = query.getExecutableCriteria(session).list();
Test测试代码:
public static void main(String[] args) throws Exception {
StudentService studentService = new StudentServiceImpl();
List<Student> list = studentService.findByProperty(new Student("三"));
for(Student s: list){
System.out.println(s.getName());
}
}
?HQL命名查询
在***.hbm.xml文件中配置

配置一个查询语句
<query name="findByName">
<![CDATA[select from Student where name like :name]]>
</query>
调用:
Dao层:
public List<Student> findByName(String name) throws Exception {
Session session = null;
Transaction transaction = null;
List<Student> list = new ArrayList<Student>();
try {
session = HibernateUtil.getSession();
transaction = session.getTransaction();
transaction.begin();
Query query = session.getNamedQuery("findByName");
query.setParameter("name", "%" + name + "%");
list = query.list();
transaction.commit();
} catch (Exception e) {
transaction.rollback();
throw e;
}
return list;
}