HQL查询
package org.leadfar.hibernate.model; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import junit.framework.TestCase; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.transform.AliasToBeanConstructorResultTransformer; import org.hibernate.transform.AliasToBeanResultTransformer; import org.leadfar.hibernate.Transfer.MyTransformer; import org.leadfar.hibernate.web.VO.PersonVO; import org.leadfar.hibernate.web.VO.PersonVOTrans; public class TestHQL extends TestCase { public void save_01() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); Random r = new Random(); for(int i=0;i<100;i++) { ContactPerson cp = new ContactPerson("李四"+i); cp.setAge(r.nextInt(99)); cp.setBirthday(new Date()); session.save(cp); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_01() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //类名、属性名对大小写敏感,关键字对大小写不敏感 //使用占位符?并给参数赋值,索引从0开始,赋值顺序严格按照顺序进行赋值,保证类型正确 String hql = "select n FroM ContactPerson n where n.age between ? and ?"; List<ContactPerson> cps = session.createQuery(hql) .setParameter(0, 10) .setParameter(1, 20) .list(); for(ContactPerson cp : cps ) { System.out.println(cp.getName()+","+cp.getAge()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_02() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //使用命名参数,参数赋值属性任意,保证赋值数据的类型正确 String hql = "select n from ContactPerson n where n.name like :mz and n.age between :lage and :mage"; List<ContactPerson> cps = session.createQuery(hql) .setParameter("lage", 10) .setParameter("mage", 20) .setParameter("mz", "张三6%") .list(); for(ContactPerson cp : cps ) { System.out.println(cp.getName()+","+cp.getAge()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_03() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //使用命名参数传递集合数据到查询语句中 String hql = "select n from ContactPerson n where n.age in (:ages)"; Integer[] ages = {15,20,32}; List<ContactPerson> cps = session.createQuery(hql) .setParameterList("ages", ages) .list(); for(ContactPerson cp : cps ) { System.out.println(cp.getName()+","+cp.getAge()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_04() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //使用命名参数传递集合数据到查询语句中 String hql = "select n from ContactPerson n where n.name in (:names)"; List<String> names = new ArrayList<String>(); names.add("张三1"); names.add("张三9"); List<ContactPerson> cps = session.createQuery(hql) .setParameterList("names", names) .list(); for(ContactPerson cp : cps ) { System.out.println(cp.getName()+","+cp.getAge()+","+cp.getBirthday()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_05() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //对null值的查询使用 is null String hql = "select n from ContactPerson n where n.group is null"; List<ContactPerson> cps = session.createQuery(hql).list(); for(ContactPerson cp : cps ) { System.out.println(cp.getName()+","+cp.getAge()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_06() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //查询部分属性--投影查询---如果不是全字段查询,那么得到的将不是ContactPerson对象,结果为一个Object[] String hql = "select n.name,n.age from ContactPerson n where n.age between :lage and :mage"; List<Object[]> cps = session.createQuery(hql) .setParameter("lage", 10) .setParameter("mage", 30) .list(); for(Object[] cp : cps ) { System.out.println((String)cp[0]+","+(Integer)cp[1]); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_07() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //唯一结果--uniqueResult String hql = "select count(*) from ContactPerson n"; long rowCount = (Long)session.createQuery(hql).uniqueResult(); System.out.println(rowCount); //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_08() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //唯一结果--uniqueResult(结果只能为0条或1条的情况下使用) String hql = "select n.age,n.birthday from ContactPerson n where n.id = 1"; Object[] obj = (Object[])session.createQuery(hql).uniqueResult(); if(obj!=null) { System.out.println((Integer)obj[0]); System.out.println((Date)obj[1]); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_09() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //查询结果的转化---转化为类的属性,再使用对象获取属性,避免通过下标访问元素的麻烦 String hql = "select new ContactPerson(n.id,n.age,n.name) from ContactPerson n where id > :lid and id < :mid"; List<ContactPerson> cps = session.createQuery(hql) .setParameter("lid", 10) .setParameter("mid", 20) .list(); for(ContactPerson cp : cps) { System.out.println(cp.getId()+","+cp.getAge()+","+cp.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_10() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //查询结果的转化---转化为类的属性,再使用对象获取属性,避免通过下标访问元素的麻烦 String hql = "select new org.leadfar.hibernate.web.VO.PersonVO(n.name,n.age,n.birthday) from ContactPerson n where id > :lid and id < :mid"; List<PersonVO> cps = session.createQuery(hql) .setParameter("lid", 10) .setParameter("mid", 20) .list(); for(PersonVO cp : cps) { System.out.println(cp.getName()+","+cp.getAge()+","+cp.getBirthday()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_11() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //查询结果的转化---转化为类的属性,再使用对象获取属性,避免通过下标访问元素的麻烦 String hql = "select new map(n.name as name,n.age as age,n.birthday as birthday) from ContactPerson n where id > :lid and id < :mid"; List<Map> cps = session.createQuery(hql) .setParameter("lid", 10) .setParameter("mid", 20) .list(); for(Map map : cps) { System.out.println(map); } //获取entry,在获取可以对应的value for(Map map : cps) { Iterator it = map.entrySet().iterator(); while(it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); System.out.print(entry.getKey()+":"+entry.getValue()); System.out.print("\t"); } System.out.println(); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_12() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //查询结果的转化---转化为map String hql = "select new map(n.name as name,n.age as age,n.birthday as birthday) from ContactPerson n where id > :lid and id < :mid"; List<Map> cps = session.createQuery(hql) .setParameter("lid", 10) .setParameter("mid", 20) .list(); for(Map map : cps) { System.out.println(map); } //获取entry,在获取可以对应的value for(Map map : cps) { System.out.println(map.get("name")+","+map.get("age")+","+map.get("birthday")); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_13() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //求总记录数 String hql = "select count(*) from ContactPerson n "; Query query = session.createQuery(hql); long rowCount = (Long)query.uniqueResult(); System.out.println("总记录数:"+rowCount); //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_14() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //分页 String hql = "select n from ContactPerson n "; Query query = session.createQuery(hql); query.setFirstResult(0);//0表示从查询结果的第一条记录开始 query.setMaxResults(5);//一次最大返回记录数(最后一页如果小于5条,则有几条返回几条) List<ContactPerson> cps = query.list(); for(ContactPerson cp : cps) { System.out.println(cp.getId()+","+cp.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_15() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //使用iterate()方法查询实体对象,会发生N+1问题---根源:hibernate缓存策略 String hql = "select n from ContactPerson n "; Query query = session.createQuery(hql); query.setFirstResult(0);//0表示从查询结果的第一条记录开始 query.setMaxResults(5);//一次最大返回记录数(最后一页如果小于5条,则有几条返回几条) Iterator<ContactPerson> it = query.iterate(); while(it.hasNext()) { ContactPerson cp = it.next(); System.out.println(cp.getId()+","+cp.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_16() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //使用iterate()方法查询 非实体 对象,与使用list()没有区别--只发出一条查询语句 String hql = "select new ContactPerson(n.id,n.name) from ContactPerson n "; Query query = session.createQuery(hql); query.setFirstResult(0);//0表示从查询结果的第一条记录开始 query.setMaxResults(5);//一次最大返回记录数(最后一页如果小于5条,则有几条返回几条) Iterator<ContactPerson> it = query.iterate(); while(it.hasNext()) { ContactPerson cp = it.next(); System.out.println(cp.getId()+","+cp.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_17() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //使用游标进行查询---表特别大时使用 String hql = "select new ContactPerson(n.id,n.name) from ContactPerson n "; Query query = session.createQuery(hql); query.setFirstResult(0);//0表示从查询结果的第一条记录开始 query.setMaxResults(5);//一次最大返回记录数(最后一页如果小于5条,则有几条返回几条) ScrollableResults results = query.scroll(ScrollMode.SCROLL_SENSITIVE); while(results.next()) { ContactPerson cp = (ContactPerson)results.get(0); System.out.println(cp.getId()+","+cp.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } /////////标准化对象查询////////////////////////// public void HQL_18() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //相当于select n from ContactPerson n Criteria criteria = session.createCriteria(ContactPerson.class); //相当于where name like "%1%" criteria.add( Restrictions.like("name", "%1%") ); List<ContactPerson> cps = criteria.list(); for(ContactPerson cp :cps) { System.out.println(cp.getId()+","+cp.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_19() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个,需要判断是否为NULL才能决定最终的查询语句 ContactPerson condition = new ContactPerson(); condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); //如果name属性不为空,则添加对name的查询条件 if(condition.getName()!=null) {//MatchMode.ANYWHERE 构建查询语句时会自动加上"%%" criteria.add(Restrictions.like("name", condition.getName(),MatchMode.ANYWHERE)); } if(condition.getBirthday()!=null) { criteria.add(Restrictions.eq("birthday", condition.getBirthday())); } if(condition.getAge()>0) { criteria.add(Restrictions.lt("age", new Integer(condition.getAge()))); } List<ContactPerson> cps = criteria.list(); for(ContactPerson c :cps) { System.out.println(c.getId()+","+c.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_20() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个 //hibernate会自动将属性非NULL的作为查询条件,其中id不论有没有值,都被忽略 ContactPerson condition = new ContactPerson(); //condition.setId(10);//id属性会被忽略,不会作为查询条件 condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); criteria.add( Example.create(condition) .enableLike(MatchMode.ANYWHERE)//所有字符串,如果不为NULL,则进行模糊查询条件 .excludeZeroes()//所有取0的值,不被作为查询条件 .excludeProperty("address") //不论address属性是否为null,都不作为构建查询条件 ); List<ContactPerson> cps = criteria.list(); for(ContactPerson c :cps) { System.out.println(c.getId()+","+c.getName()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_21() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个 //hibernate会自动将属性非NULL的作为查询条件,其中id不论有没有值,都被忽略 ContactPerson condition = new ContactPerson(); //condition.setId(10);//id属性会被忽略,不会作为查询条件 condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); criteria.add( Example.create(condition) .enableLike(MatchMode.ANYWHERE)//所有字符串,如果不为NULL,则进行模糊查询条件 .excludeZeroes()//所有取0的值,不被作为查询条件 .excludeProperty("address") //不论address属性是否为null,都不作为构建查询条件 ); //select name 查询单个属性 criteria.setProjection( Projections.property("name") ); List<String> names = criteria.list(); for(String name : names) { System.out.println(name); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_22() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个 //hibernate会自动将属性非NULL的作为查询条件,其中id不论有没有值,都被忽略 ContactPerson condition = new ContactPerson(); //condition.setId(10);//id属性会被忽略,不会作为查询条件 condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); criteria.add( Example.create(condition) .enableLike(MatchMode.ANYWHERE)//所有字符串,如果不为NULL,则进行模糊查询条件 .excludeZeroes()//所有取0的值,不被作为查询条件 .excludeProperty("address") //不论address属性是否为null,都不作为构建查询条件 ); //select name,age,birthday 查询多个属性 criteria.setProjection( Projections.projectionList() .add(Projections.property("name")) .add(Projections.property("age")) .add(Projections.property("birthday")) ); List<Object[]> objs = criteria.list(); for(Object[] obj : objs) { System.out.println(obj[0]+","+obj[1]+","+obj[2]); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_23() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个 //hibernate会自动将属性非NULL的作为查询条件,其中id不论有没有值,都被忽略 ContactPerson condition = new ContactPerson(); //condition.setId(10);//id属性会被忽略,不会作为查询条件 condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); criteria.add( Example.create(condition) .enableLike(MatchMode.ANYWHERE)//所有字符串,如果不为NULL,则进行模糊查询条件 .excludeZeroes()//所有取0的值,不被作为查询条件 .excludeProperty("address") //不论address属性是否为null,都不作为构建查询条件 ); //select name,age,birthday 查询多个属性 criteria.setProjection( Projections.projectionList() .add(Projections.property("name"),"p_name") .add(Projections.property("age"),"p_age") .add(Projections.property("birthday"),"p_birthday") ); //转化结果为Map类型 //需要为属性取别名 alias ---限制:别名不能与属性名相同 criteria.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP); List<Map> objs = criteria.list(); for(Map obj: objs) { System.out.println(obj); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_24() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个 //hibernate会自动将属性非NULL的作为查询条件,其中id不论有没有值,都被忽略 ContactPerson condition = new ContactPerson(); //condition.setId(10);//id属性会被忽略,不会作为查询条件 condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); criteria.add( Example.create(condition) .enableLike(MatchMode.ANYWHERE)//所有字符串,如果不为NULL,则进行模糊查询条件 .excludeZeroes()//所有取0的值,不被作为查询条件 .excludeProperty("address") //不论address属性是否为null,都不作为构建查询条件 ); //select name,age,birthday 查询多个属性 criteria.setProjection( Projections.projectionList() .add(Projections.property("name"),"name") .add(Projections.property("age"),"age") .add(Projections.property("birthday"),"birthday") ); //转化结果为VO //需要为属性取别名 alias ---限制:别名不能与属性名相同 //不取别名:[could not execute query] //VO中的setters方法需要与别名一致 ,即Property与别名一致 //setters的property不一致:[Could not find setter for p_name on class org.leadfar.hibernate.web.VO.PersonVO] //另一种办法:自定义一个转化类将别名转化为与property一致的名称,然后就行了 criteria.setResultTransformer(new AliasToBeanResultTransformer(PersonVO.class)); List<PersonVO> objs = criteria.list(); for(PersonVO obj: objs) { System.out.println(obj); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_25() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个 //hibernate会自动将属性非NULL的作为查询条件,其中id不论有没有值,都被忽略 ContactPerson condition = new ContactPerson(); //condition.setId(10);//id属性会被忽略,不会作为查询条件 condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); criteria.add( Example.create(condition) .enableLike(MatchMode.ANYWHERE)//所有字符串,如果不为NULL,则进行模糊查询条件 .excludeZeroes()//所有取0的值,不被作为查询条件 .excludeProperty("address") //不论address属性是否为null,都不作为构建查询条件 ); //select name,age,birthday 查询多个属性 criteria.setProjection( Projections.projectionList() .add(Projections.property("name"),"p_name") .add(Projections.property("age"),"p_age") .add(Projections.property("birthday"),"p_birthday") ); //转化结果为VO //需要为属性取别名 alias ---限制:别名不能与属性名相同 //不取别名:[could not execute query] //VO中的setters方法需要与别名一致 ,即Property与别名一致 //setters的property不一致:[Could not find setter for p_name on class org.leadfar.hibernate.web.VO.PersonVO] //---------------------------------------------------------------- //另一种办法:自定义一个转化类将别名转化为与property一致的名称,然后就行了 //依赖于setters方法,转化后就能通过setters方法进行赋值,然后VO对象将结果进行包装 //注:通过转化类将别名设置为与property一致的名称,而没有改变VO中的property名称!!! criteria.setResultTransformer(new MyTransformer(PersonVOTrans.class)); List<PersonVOTrans> objs = criteria.list(); for(PersonVOTrans obj: objs) { System.out.println(obj.getName()+","+obj.getBirthday()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_26() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 //模拟从页面传入查询参数,有可能有多个,有可能只有一个 //hibernate会自动将属性非NULL的作为查询条件,其中id不论有没有值,都被忽略 ContactPerson condition = new ContactPerson(); //condition.setId(10);//id属性会被忽略,不会作为查询条件 condition.setName("李四"); condition.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2012-9-14")); condition.setAge(20); Criteria criteria = session.createCriteria(ContactPerson.class); criteria.add( Example.create(condition) .enableLike(MatchMode.ANYWHERE)//所有字符串,如果不为NULL,则进行模糊查询条件 .excludeZeroes()//所有取0的值,不被作为查询条件 .excludeProperty("address") //不论address属性是否为null,都不作为构建查询条件 ); //select name,age,birthday 查询多个属性 criteria.setProjection( Projections.projectionList() .add(Projections.property("name")) .add(Projections.property("age")) .add(Projections.property("birthday")) ); //---------------------------------------------------------------- //转化结果为VO---不需要为属性取别名 criteria.setResultTransformer( new AliasToBeanConstructorResultTransformer( PersonVO.class.getConstructor(String.class,Integer.class,Date.class) ) ); List<PersonVO> objs = criteria.list(); for(PersonVO obj: objs) { System.out.println(obj.getName()+","+obj.getBirthday()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } ////////////////////////////原生SQL////////////////// public void HQL_27() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 String sql = "select * from t_person"; SQLQuery query = session.createSQLQuery(sql); List<Object[]> obj = query.list(); for(Object[] o : obj) { System.out.println(o[0]+","+o[1]+","+o[2]); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_28() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 String sql = "select * from t_person"; SQLQuery query = session.createSQLQuery(sql); //包装为实体对象,必须是全字段查询。部分属性查询不能使用对象进行包装 query.addEntity(ContactPerson.class); List<ContactPerson> obj = query.list(); for(ContactPerson o : obj) { System.out.println(o.getName()+","+o.getAge()+","+o.getBirthday()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_29() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); //基于对象的标准化查询,以对象的方式替代sql语句 String sql = "select name,age from t_person"; SQLQuery query = session.createSQLQuery(sql); //包装为实体对象,必须是全字段查询。 //部分属性查询不能使用对象进行包装 //属性与字段名必须一致 query.addEntity(ContactPerson.class); List<ContactPerson> obj = query.list(); for(ContactPerson o : obj) { System.out.println(o.getName()+","+o.getAge()+","+o.getBirthday()); } //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close();//session关闭之后,user对象处于离线Detached状态 } } public void HQL_30() throws Exception { Configuration cfg = new Configuration().configure(); SessionFactory sfactory = cfg.buildSessionFactory(); Session session = sfactory.openSession(); try { //开启事务 session.beginTransaction(); String sql = "update t_person set birthday = ? where id < ?"; SQLQuery query = session.createSQLQuery(sql); query.setParameter(0, new Date()); query.setParameter(1, 30); //update,delete,insert query.executeUpdate(); //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //出现异常,回滚事务 session.getTransaction().rollback(); } finally { //关闭session session.close(); } } }
VO
package org.leadfar.hibernate.web.VO; import java.text.SimpleDateFormat; import java.util.Date; public class PersonVO { private SimpleDateFormat format = new SimpleDateFormat("yy年MM月dd日"); private String name; private int age; private String birthday; public PersonVO() {} public PersonVO(String name, Integer age, Date birthday) { this.name = name; this.age = age; this.birthday = format.format(birthday); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } }
package org.leadfar.hibernate.web.VO; import java.text.SimpleDateFormat; import java.util.Date; public class PersonVOTrans { private String name; private int age; private Date birthday; public PersonVOTrans() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
package org.leadfar.hibernate.Transfer; import java.io.Serializable; import java.util.Arrays; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.property.ChainedPropertyAccessor; import org.hibernate.property.PropertyAccessor; import org.hibernate.property.PropertyAccessorFactory; import org.hibernate.property.Setter; import org.hibernate.transform.ResultTransformer; public class MyTransformer implements ResultTransformer, Serializable{ /** * */ private static final long serialVersionUID = -8264738346888035746L; private final Class resultClass; private boolean isInitialized; private String[] aliases; private Setter[] setters; public MyTransformer(Class resultClass) { if ( resultClass == null ) { throw new IllegalArgumentException( "resultClass cannot be null" ); } isInitialized = false; this.resultClass = resultClass; } public Object transformTuple(Object[] tuple, String[] aliases) { Object result; try { if ( ! isInitialized ) { initialize( aliases ); } else { check( aliases ); } result = resultClass.newInstance(); for ( int i = 0; i < aliases.length; i++ ) { if ( setters[i] != null ) { setters[i].set( result, tuple[i], null ); } } } catch ( InstantiationException e ) { throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() ); } catch ( IllegalAccessException e ) { throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() ); } return result; } private void initialize(String[] aliases) { PropertyAccessor propertyAccessor = new ChainedPropertyAccessor( new PropertyAccessor[] { PropertyAccessorFactory.getPropertyAccessor( resultClass, null ), PropertyAccessorFactory.getPropertyAccessor( "field" ) } ); this.aliases = new String[ aliases.length ]; setters = new Setter[ aliases.length ]; for ( int i = 0; i < aliases.length; i++ ) { String alias = aliases[ i ]; if ( alias != null ) { this.aliases[ i ] = alias; //setters[ i ] = propertyAccessor.getSetter( resultClass, alias ); //将别名转化为与PersonVO中的property一致的名称 setters[ i ] = propertyAccessor.getSetter( resultClass, alias.substring(2) ); } } isInitialized = true; } private void check(String[] aliases) { if ( ! Arrays.equals( aliases, this.aliases ) ) { throw new IllegalStateException( "aliases are different from what is cached; aliases=" + Arrays.asList( aliases ) + " cached=" + Arrays.asList( this.aliases ) ); } } public List transformList(List collection) { return collection; } public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } MyTransformer that = ( MyTransformer ) o; if ( ! resultClass.equals( that.resultClass ) ) { return false; } if ( ! Arrays.equals( aliases, that.aliases ) ) { return false; } return true; } public int hashCode() { int result = resultClass.hashCode(); result = 31 * result + ( aliases != null ? Arrays.hashCode( aliases ) : 0 ); return result; } }
实体类
package org.leadfar.hibernate.model; public class Group { private int id; private String name; public Group() { // TODO Auto-generated constructor stub } public Group(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package org.leadfar.hibernate.model; import java.util.Date; public class ContactPerson { private int id; private String name; private int age; private Date birthday; private Group group; public ContactPerson() { } public ContactPerson(String name) { this.name = name; } public ContactPerson(int id,String name) { this.id = id; this.name = name; } public ContactPerson(int id,int age,String name) { this.id = id; this.age = age; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.hibernate.auction"> <!-- name为实体类 table为映射到数据库中的表 lazy默认为true 延迟发出select语句,直到真正用到对象的属性(非id属性)--> <class name="org.leadfar.hibernate.model.Group" table="t_group" > <!-- id为数据库标识,作为主键 --> <id name="id"> <generator class="native"/> </id> <property name="name"/> </class> </hibernate-mapping>
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.hibernate.auction"> <!-- name为实体类 table为映射到数据库中的表 lazy默认为true 延迟发出select语句,直到真正用到对象的属性(非id属性)--> <class name="org.leadfar.hibernate.model.ContactPerson" table="t_person" > <!-- id为数据库标识,作为主键 --> <id name="id"> <generator class="native"/> </id> <property name="name"/> <property name="age"></property> <property name="birthday" type="date"></property> <many-to-one name="group" column="gid"></many-to-one> </class> </hibernate-mapping>
相关推荐
本篇文章将深入探讨Hibernate中的三种主要查询方式:HQL(Hibernate Query Language)、Criteria API以及原生SQL。 一、HQL(Hibernate Query Language) HQL是Hibernate提供的一种面向对象的查询语言,它类似于SQL...
【描述】:在ORM框架Hibernate中,数据查询和检索是一个核心功能,它提供了多种查询方式,包括标准化对象查询(Criteria Query)、Hibernate查询语言(HQL)和原生SQL查询。其中,HQL作为官方推荐的查询方式,具有...
然而,尽管Hibernate提供了强大的HQL(Hibernate Query Language)和Criteria API,但在处理某些特定的、复杂的SQL查询时,可能无法满足需求,这时就需要用到“原生的Native SQL查询”。 Native SQL查询允许我们...
3. **平台无关**:由于HQL是基于Hibernate框架的查询语言,因此不受特定数据库的影响,可以在不同的数据库平台上无缝迁移。 4. **灵活性**:HQL支持多种查询方式,包括简单查询、复杂查询、联接查询等。 ### HQL的...
使用HQL(Hibernate Query Language)或Criteria API替代原生SQL,可以让Hibernate更好地优化查询。它们可以利用Hibernate的元数据信息生成更高效的SQL,同时避免SQL注入风险。 4. **分页查询**: 当处理大量数据...
本文将详细介绍Hibernate的五种查询方式,包括HQL查询、Criteria方法、动态查询DetachedCriteria、例子查询、SQL查询以及命名查询,以满足不同场景下的需求。 1. HQL查询: Hibernate Query Language(HQL)是一种...
1. 合理使用HQL与SQL:对于复杂的数据库操作,可能需要结合使用HQL和原生SQL。 2. 避免在HQL中使用SQL函数:尽量用Hibernate提供的函数,以确保跨数据库兼容性。 3. 优化查询性能:合理设计数据库索引,避免全表扫描...
- **应用场景**:对于一些复杂的查询,可以直接使用原生SQL语句。 - **示例**: ```java String sql = "SELECT * FROM Employee WHERE empName = ?"; SQLQuery query = session.createSQLQuery(sql).addEntity...
本案例中,开发者遇到了一个与Hibernate映射配置文件相关的异常,该异常涉及到不支持的“union”联合查询。具体表现为在执行查询时抛出了`SQLGrammarException`,提示为`ORA-00907: 缺失右括号`,这通常意味着SQL...
总结,Hibernate提供了多种方式查询所有数据,包括HQL、Criteria API和原生SQL。选择哪种方式取决于个人偏好和具体需求。无论哪种方法,都应确保事务管理的正确性,以确保数据的一致性。在实际开发中,还需注意性能...
综上所述,Hibernate的Criteria API提供了一种灵活、类型安全的方式来构造查询,它可以适应多种查询需求,同时也能够与HQL和原生SQL查询结合使用,从而满足开发者的不同需求。掌握Criteria API的使用,对于提高在...
在执行数据库操作时,可以根据业务逻辑动态地决定使用哪种查询方式,如Criteria、HQL或原生SQL。 四、最佳实践与注意事项 4.1 安全性 动态SQL可能导致SQL注入风险,因此在拼接HQL或Criteria时,应确保参数安全,...
HQL 是 Hibernate 自带的一种类似于 SQL 的查询语言,它可以用来执行各种数据库操作。HQL 支持面向对象的语法,使得查询更加直观。 - **标准 HQL** - **读取数据** - `select` 子句用于指定要获取的数据字段。 -...
10. **查询语言**:Hibernate支持HQL(Hibernate Query Language)和Criteria API,它们都是面向对象的查询方式,比原生SQL更符合面向对象编程的思想。 理解并正确使用这些DTD文件对于有效配置和使用Hibernate至关...
在 Hibernate 中,Criteria API 提供了一种类型安全的方式来构建动态查询,与 HQL 相比,它更加面向对象,并且支持更复杂的查询条件。 #### 二、基本概念 1. **Criteria**:`org.hibernate.Criteria` 接口是 ...
Hibernate 的核心功能之一是提供了一套强大的查询接口和方法,包括基于对象的查询、SQL 查询和 HQL (Hibernate Query Language) 查询等。本文将详细介绍 Hibernate 提供的几种查询方式及其应用场景。 #### 二、重要...
标题“一个基于原生Java代码查询方式的JPA查询框架.zip”指的是一个使用Java Persistence API(JPA)的查询框架,该框架允许开发者使用原生的Java代码进行数据库查询,而不是依赖于HQL(Hibernate Query Language)...
Hibernate提供了多种查询方式,包括HQL(Hibernate Query Language)、Criteria Query和SQL查询。 1. Criteria Query: Criteria Query 是一种面向对象的查询方式,它允许我们通过构建Criteria对象来表示查询条件...
Hibernate 支持 native SQL 操作,可以使用原生 SQL 语句来查询对象。 性能 Hibernate 的性能可以通过一级缓存和二级缓存来提高。一级缓存可以缓存对象的状态,二级缓存可以缓存查询结果。 Hibernate 也支持第三方...