hql(都要在事务中完成)
session.beginTransaction();
session.getTransaction().commit();
session.beginTransaction(); //User指的是类,不是表名 username指的是属性,不是列名 String hql = "from User as u where u.username = 'u1'"; Query query = session.createQuery(hql); List<User> list = query.list(); for(User user : list) { System.out.println(user.getId() + " : " + user.getUsername()); } session.getTransaction().commit();
获取不完整对象
String hql = "select username from User"; Query query = session.createQuery(hql); // 不再是User而是String List<String> list = query.list(); for(String name : list) { System.out.println(name); } String hql = "select id,username,password from User"; Query query = session.createQuery(hql); List<Object[]> list = query.list(); for(Object[] array : list) { System.out.println(array[0] + " : " + array[1]); } //即使把所有属性都写上还是String类型 只有写from User才是User类型 String hql = "from User where id = 1"; Query query = session.createQuery(hql); //这样写的前提是确保只有一条结果记录 User user = (User) query.uniqueResult(); System.out.println(user.getUsername()); String hql = "select count(*) from User"; Query query = session.createQuery(hql); // 这样写的前提是确保只有一条结果记录 Long count = (Long) query.uniqueResult(); System.out.println("count:" + count); String hql = "select count(*),max(id) from User"; Query query = session.createQuery(hql); Object[] count = (Object[]) query.uniqueResult(); System.out.println("count:" + count[0] + " maxId:" + count[1]);
HQL占位符
String hql = "from User as u where u.username = ?"; Query query = session.createQuery(hql); //hibernate从0开始数 // 方式1 query.setString(0, "u1"); // 方式2,不用考虑数据类型 query.setParameter(0, "jack"); List<User> list = query.list(); for(User user : list) { System.out.println(user.getId() + " : " + user.getUsername()); }
HQL引用占位符
String hql = "from User as u where u.username = :name and u.password = :pwd"; Query query = session.createQuery(hql); // 只能用setParameter query.setParameter("name", "jack"); query.setParameter("pwd", "123"); List<User> list = query.list(); for(User user : list) { System.out.println(user.getId() + " : " + user.getUsername()); }
分页
String hql = "from User"; Query query = session.createQuery(hql); query.setFirstResult(10); query.setMaxResults(5); List<User> list = query.list(); for(User user : list) { System.out.println(user.getId() + " : " + user.getUsername()); }