标签:hibernate
一:query接口的使用
通过query接口我们可以完成更加复杂的查询任务.
举例: 通过用户来查询数据.
query中分页查询的原理:
Query query =session.createQuery(“from User”);
query.setFirstResult(0); //从哪一条记录开始查询
query.setMaxResults(2); //每页显示多少条记录
List userList =query.list(); //将查出来的对象自动生成list对象返回
案例代码如下:
public class Test {
public static void main(String[] args) {
Session session=HibernateUtil.getCurrentSession();
Transaction ts=null;
try {
ts=session.beginTransaction();
//获取query引用[这里 Users不是表.而是domain类名]
//[where 后面的条件可以是类的属性名,也可以是表的字段,安照hibernate规定,我们还是应该使用类的属性名.]
Query query=session.createQuery("from Users where name=‘nihao‘");
//通过list方法获取结果,这个list会自动的将封装成对应的domain对象
//所以我们jdbc进行二次封装的工作没有.
List<Users> list=query.list();
for(Users user:list){
System.out.println(user.getEmail()+"=="+user.getTel());
}
ts.commit();
} catch (Exception e) {
//发生异常,回滚所以操作
if(ts!=null){
ts.rollback();
}
throw new RuntimeException(e.getMessage());
}finally{
//关闭session
if(session!=null&&session.isOpen()){
session.close();
}
}
}
}
程序运行结果:
Hibernate: select users0_.id as id0_, users0_.name as name0_, users0_.email as email0_, users0_.pwd as pwd0_, users0_.tel as tel0_, users0_.grade as grade0_ from users users0_ where users0_.name=‘nihao‘
zhangfei@sohu.com==110
二:criteria接口的使用
public class Test {
public static void main(String[] args) {
Session session=HibernateUtil.getCurrentSession();
Transaction ts=null;
try {
ts=session.beginTransaction();
Criteria cri=session.createCriteria(Users.class)
.setMaxResults(2).addOrder(Order.desc("id"));
List<Users> list=cri.list();
for(Users user:list){
System.out.println(user.getId());
}
ts.commit();
} catch (Exception e) {
//发生异常,回滚所以操作
if(ts!=null){
ts.rollback();
}
throw new RuntimeException(e.getMessage());
}finally{
//关闭session
if(session!=null&&session.isOpen()){
session.close();
}
}
}
查询结果:
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.email as email0_0_, this_.pwd as pwd0_0_, this_.tel as tel0_0_, this_.grade as grade0_0_ from users this_ order by this_.id desc
limit ?
101
100
版权声明:博主原创文章,转载请说明出处。http://blog.csdn.net/dzy21
标签:hibernate
原文地址:http://blog.csdn.net/dzy21/article/details/47780401