手记

hibernate查询方式学习记录

OID查询

//根据id查询返回一个对象
User user = session.get(User.class,1);

HQL查询
HQL查询是操作实体类对象,并不是操作数据库表

1.查询所有

//创建Query对象
Query query = session.creatQuery("from User");
//调用方法得到结果,结果是一个List集合
List<User> list = query.list();
//遍历
for(User user : list){
    System.out.print(user.getName);
}

2.条件查询

Query query = session.creatQuery("from User where uid=? and userName=?");
//设置问号值
query.setParameter(0,1);
quert.setParameter(1,"melon");
List<User> list = query.list();
//模糊查询
Query query = session.creatQuery("from User where userName like ?");
query.setParameter(0,"%m%");
List<User> list = query.list();

3.排序查询

//asc:升序查询 desc:降序查询
Query query = session.creatQuery("from User order by uid asc");
list<User> list = query.list();

4.分页查询

 Query query = session.creatQuery("from User");
 //设置开始位置
 query.setFirstResult(0);
 //设置每页记录数
 query.setMaxResult(3);
 List<User> list = query.list();

5.投影查询

 Query query = session.creatQuery)("select userName from User");
 List<Object   > list = query.list();

HQL多表查询
1.内连接和迫切内连接

//内连接查询
Query query = session.creatQuery(form User inner join sellerSet);
//迫切内连接
Query query = session.creatQuery(form User inner join fetch sellerSet);
//内连接返回的是数组对象,迫切内连接返回的是实体类对象
List<User> list = query.list();

2.左外连接和迫切左外连接

//左外连接查询
Query query = session.creatQuery(form User left outer join sellerSet);
//迫切左外连接
Query query = session.creatQuery(form User left outer join fetch sellerSet);
//左连接返回的是数组对象,迫切左连接返回的是实体类对象
List<User> list = query.list();

3.右外连接,参考左外连接,没有迫切右外连接

QBC查询
1.查询全部

//创建对象
 Criteria criteria = session.creatCriteria(User.class);
 List<User> list = criteria.list();

2.条件查询

Criteria criteria = session.creatCriteria(User.class);
//调用add方法表示添加查询条件
//Restrictions.eq方法是相当于sql语句的==判断,第一个属性值填实体类属性名,第二个值填属性值
criteria.add(Restrictions.eq("cid",1));
criteria.add(Restrictions.eq("userName","melon"));
List<User> list = criteria.list();
//模糊查询
Criteria criteria = session.creatCriteria(User.class);
////Restrictions.like方法是相当于sql语句的like判断,第一个属性值填实体类属性名,第二个值填属性值
criteria.add(Restrictions.like("userName","%m%"));
List<User> list = criteria.list();

3.排序查询

Criteria criteria = session.creatCriteria(User.class);
//调用addOrder方法,里面调用Order对象的asc方法或desc方法
//asc方法或desc方法里面填写实体类属性名称
criteria.addOrder(Order.asc("uid"));
criteria.addOrder(Order.desc("uid"));
List<User> list = criteria.list();

4.统计查询

Criteria criteria = session.creatCriteria(User.class);
criteria.setProjection(Projections.rowCount());
Object obj = criteria.uniqueResult();
Long lobj = (Long)obj;
int count = lobj.intValue();

5.离线查询。。后补

0人推荐
随时随地看视频
慕课网APP