0
点赞
收藏
分享

微信扫一扫

HQL数据查询(Hibernate推荐)


 HQL是Hbernate官方推荐使用的查询语句


HQL的语句形式:select...from...where..group by..having...order by...


HQL对关键字大小写不敏感,习惯上小小小写,对JAVA等属性名称大小写敏感




     ---Query的使用----


例:String hql="from Sellor";//Sellor是一个类名


    Query query=session.createQuery(hql);


    List<Sellor>  sellors=query.list();


    for循环查看数据



别名的使用


    String hql=“from Sellor  as  sellor”


或者 String hql=“from Sellor   sellor”




-----------select语句


1以Object[]形式返回选择的属性


  默认情况下是这种形式


  String hql="select s.name, s.tel from Seller s";


  Query query=session.createQuery(hql);


  List<Object[]> lists=query.list();


  for(Object[] objs:lists){ syso(objs[0])}


  注意:如果select后面只有一个属性,将返回object类型


  




2以List形式返回选择的属性


   String hql="select new list(s.name, s.tel) from Seller s";


  Query query=session.createQuery(hql);


  List<list> lists=query.list();


  for(List list:lists){ syso(list.get(0))}







3以map形式返回选择的属性


   String hql="select new Map(s.name, s.tel) from Seller s";


  Query query=session.createQuery(hql);


  List<Map> maps=query.list();


  for(Map list:maps){ syso(map.get("name"))}








4以自定义类型返回选择的属性(选哪几个属性在类里面建包含这几个属性的构造器)


   String hql="select new Sellor(s.name, s.tel) from Seller s";


  Query query=session.createQuery(hql);


  List<Seller> sellers=query.list();


  for(Seller seller:sellers){ syso(  seller.getName();     )}


   





5以获取独特的结果-distinct关键字


   使用distinct关键字去除查询结果中的重复元素


String hql="select distinct s.xingbie from Seller s";











----------where 限制语句


String hql="from Commodity c where c.price>40";


String hql="from Commodity c where c.price is null";


String hql="from Commodity c where c.price in  (20,40)";


String hql="from Commodity c where c.price between 20 and 40";


字符串匹配


  1 like 关键字


  2 %  任意个字符


    _  一个字符




查询单个对象


  String hql="from Commodity c where c.price =30";




order by关键字


  String hql="from Commodity c order by  price asc";


举报

相关推荐

0 条评论