对象导航查询和OID查询代码实现:
@Test
public void testSelect1() {
Session session = HibernateUtils.getSession();
Transaction ts = null;
try {
ts = session.beginTransaction();
User user = (User)session.get(User.class, 14);
System.out.println(user.getRoleSet().size());
Iterator<Role> it = user.getRoleSet().iterator();
for (;it.hasNext();) {
Role role = (Role) it.next();
System.out.println(role.getRole_name() + " " + role.getRole_memo());
}
ts.commit();
} catch (Exception e) {
ts.rollback();
e.printStackTrace();
}
}
2、hql语句查询
普通的sql语句操作数据表和字段,hql操作实体类和属性
具体的实现如下:
try {
ts = session.beginTransaction();
Query query = session.createQuery("from User");
List<User> list = query.list();
for (User user : list) {
System.out.println(user.toString());
}
ts.commit();
条件查询:
实现代码:
query = session.createQuery("from User where username like? order by uid desc");
query.setParameter(0, "w%");
@SuppressWarnings("unchecked")
List<User> list1 = (List<User>)query.list();
for(User user : list1) {
System.out.println(user.toString()+ user.getUid());
}
ts.commit();
3、排序查询
asc(升序)
select * from user order by uid desc;
4、分页查询
select * from User limit 0,3
表示开始位置是0,每页显示三行
4、投影查询
select uid,username from user;
代码实现:
//hql语句包含投影查询以及模糊查询以及排序查询
query = session.createQuery("select username from User where username like? order by uid desc");
query.setParameter(0, "w%");
//实现分页查询 设置分页开始的id值的最小值以及每页的最大项
query.setFirstResult(0);
query.setMaxResults(3);
List<Object> list1 = query.list();
for(Object object : list1) {
System.out.println(object);
}
ts.commit();
5、聚集函数使用
sum、avg、count、max、min
需要注意的地方是:
用聚集函数获得的对象要先强制转换为Long对象,在转换为int基本类型 。
否则会报错:
query = session.createQuery("select count(*) from User where username like? order by uid desc");
query.setParameter(0, "w%");
Long count = (Long)query.uniqueResult();
int countw = count.intValue();
System.out.println(countw);
ts.commit();