第十七章 离线,命名查询

[img]http://dl.iteye.com/upload/attachment/243947/57d2fbb8-0aa0-357c-a3cd-700d0dccf61e.bmp[/img]

离线查询
在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文件中配置

[img]http://dl.iteye.com/upload/attachment/243949/d97c9a6a-5e92-3165-b874-6fde14d819b7.bmp[/img]

配置一个查询语句
<query name="findByName">
<![CDATA[select from Student where name like :name]]>
</query>

调用:

[img]http://dl.iteye.com/upload/attachment/243951/b4d66835-6cea-3fd0-9213-bd5caee17934.bmp[/img]

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值