一、实体类直接查询
hql语句:(没有select * 表示默认选择全部属性)
1 public static String GET_ALLUSERINFO="from UserEntity";
测试:
1 @Test 2 public void tests(){ 3 SessionFactory sessionFactory = app.getBean("sessionFactory",SessionFactory.class); 4 Session session = sessionFactory.openSession(); 5 List<UserEntity> ulist = session.createQuery(HqlConstant.GET_ALLUSERINFO).list(); 6 if(ulist.size()>0 && ulist.get(0) != null){ 7 for(int i=0;i<ulist.size();i++){ 8 System.out.println(ulist.get(i).getUsername()); 9 } 10 } 11 }
hql语句中的UerEntity是实体类的名称,区分大小写
二、查询类的部分属性
1.构造器方式声明要获取的对象的属性字段(hql语句中有实例化了UserEntity的一个构造器,在查询的时候只会查询出该实体类中被构造器初始化的两个字段的值,前提是实体类必须有该构造器,返回的查询结果是一个UserEntity对象)
1 public static String GET_USERINFO_BY_CONSTRUCT = "select new UserEntity(username,password) from UserEntity";
2.直接声明选择参数(跟sql语句类似的查询语句,只是from后面是对象实体类名而不是数据库表名)
1 public static String GET_USERINFO_IN_SOME = "select username,address from UserEntity" ;
该查询方法返回的是一个Object对象,想要获取对象的值可以将其转换成对象数组然后取值
1 @Test 2 public void constructTest(){ 3 SessionFactory sessionFactory = app.getBean("sessionFactory",SessionFactory.class); 4 Session session = sessionFactory.openSession(); 5 6 List<Object> ulist = session.createQuery(HqlConstant.GET_USERINFO_IN_SOME).list(); 7 if(ulist.size()>0 && ulist.get(0) != null){ 8 for(int i=0;i<ulist.size();i++){ 9 System.out.println(((Object[])ulist.get(i))[0]);//转成Object数组 10 } 11 } 12 }
三、hql更新和删除(需要开启事务)
1 /** 2 * 删除数据(hibernate执行delete和update,insert都要有事务支持) 3 */ 4 public static String DELETE_USERINFO_BY_ID = "delete from UserEntity where id = 101"; 5 public static String UPDATE_USERINFO_BY_ID = "update UserEntity set username='改名字' where id=102";
测试:
1 Transaction transaction = session.beginTransaction(); 2 int retNum = 0; 3 try { 4 retNum = session.createQuery(HqlConstant.DELETE_USERINFO_BY_ID).executeUpdate(); 5 transaction.commit(); 6 } catch (Exception e) { 7 if(transaction.isActive()){ 8 transaction.rollback(); 9 } 10 e.printStackTrace(); 11 }finally { 12 session.close(); 13 }
四、参数绑定
1 /** 2 * 参数绑定查询 3 */ 4 public static String PRO_BINDING_BY_POSITIONG = "from UserEntity where id = ?";//通过位置赋值 5 public static String PRO_BINDING_BY_NAME = "from UserEntity where id = :id";//通过参数命赋值 6 public static String PRO_BINDING_BY_NAME_ARRAY = "from UserEntity where id in (:id)";//通过参数名传入数组
测试
1 List<UserEntity> ulist = session.createQuery(HqlConstant.PRO_BINDING_BY_POSITION).setParameter(0,1).list(); 2 List<UserEntity> ulist = session.createQuery(HqlConstant.PRO_BINDING_BY_NAME).setParameter("id",1).list(); 3 List<UserEntity> ulist = session.createQuery(HqlConstant.PRO_BINDING_BY_NAME_ARRAY).setParameterList("id",new Object[]{1,102}).list();
=================