Hibernate-Criteria学习笔记 「爱情、让人受尽委屈。」 2021-10-18 07:12 433阅读 0赞 # hibernate\_jpa注解 # > 目前最新版的hibernate,5.2,底层整合了jpa,用[idea的hibernate工具生成实体][idea_hibernate]时,实体包含了注解的配置文件,缺一不可 如,用户类实体,生成之后是这样子的 ![1622529-20190804162258012-455446086.png][] ![1622529-20190804162321165-780651703.png][] ![1622529-20190804162401283-51449520.png][] cascade属性的可能值有 all: 所有情况下均进行关联操作,即save-update和delete。 none: 所有情况下均不进行关联操作。这是默认值。 save-update: 在执行save/update/saveOrUpdate时进行关联操作。 delete: 在执行delete 时进行关联操作。 all-delete-orphan: 当一个节点在对象图中成为孤儿节点时,删除该节点。 比如在一个一对多的关系中,Student包含多个book,当在对象关系中删除一个book时, 此book即成为孤儿节点。 # hibernate\_Criteria用法『[转][Link 1]』 # ### 外键查询 ### 1. 对于外键本身 public Resume findByUserId(Long id) { Criteria cr=getCurrentSession().createCriteria(Resume.class); cr.add(Restrictions.eq("user.id",id)); return (Resume) cr.list().get(0); } 2. 对于外键对象的属性 public Resume findByAttr(Attr attr) { Criteria cr=getCurrentSession().createCriteria(Resume.class); cr.createAlias("user","u"); cr.add(Restrictions.eq("u.attr",attr)); return cr.list(); } # hibernate\_Restrictions用法『[转][Link 2]』 # <table style="border-color:#000000;border-width:0px;border-style:solid;"> <tbody> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;"> 方法</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;"> 说明</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.eq</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;">=</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.allEq</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;">利用Map来进行多个等于的限制</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.gt</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;">></span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.ge</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;">>=</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.lt</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;"><</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.le</span></span></td> <td><span style="font-size:18px;font-family:arial, helvetica, sans-serif;"><=</span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.between</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;">BETWEEN</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.like</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;">LIKE</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.in</span></span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;">in</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.and</span></span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">and</span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.or</span></span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">or</span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">Restrictions.isNull</span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;"><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">判断属性是否为空,为空则返回true</span></span></span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">Restrictions.isNotNull</span></td> <td><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">与isNull相反</span></span></td> </tr> <tr> <td><span style="font-size:18px;"><span style="font-family:Arial;">Restrictions.sqlRestriction</span></span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">用SQL限定查询</span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">Order.asc</span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;"><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">根据传入的字段进行升序排序</span></span></span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">Order.desc</span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;"><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">根据传入的字段进行降序排序</span></span></span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">MatchMode.EXACT</span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;"><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">字符串精确匹配.相当于"like 'value'"</span></span></span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">MatchMode.ANYWHERE</span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;"><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">字符串在中间匹配.相当于"like '%value%'"</span></span></span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">MatchMode.START</span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;"><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">字符串在最前面的位置.相当于"like 'value%'"</span></span></span></td> </tr> <tr> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;">MatchMode.END</span></td> <td><span style="font-family:arial, helvetica, sans-serif;font-size:18px;"><span style="font-size:18px;"><span style="font-family:Arial;color:#000000;">字符串在最后面的位置.相当于"like '%value'"</span></span></span></td> </tr> </tbody> </table> Disjunction:逻辑或【or】 Conjunction:逻辑与【and】 # 一、进行子查询并分页 # ## 背景: ## > 有一张活动表(volunteer\_activity) > > 和一张活动报名表(volunteer\_sign\_up)–存放志愿者活动报名记录 > > ***要求:查出志愿者参加的活动和未参加的活动*** ## 代码: ## /** * 查询已加入的活动 * @param key * @param setPageSize * @return */ @Override public PageBean findAllVolunteerJoinActivity(String key, PageBean<VolunteerActivityEntity> setPageSize, String userId) { Session session = sessionFactory.openSession(); /** * hibernate 利用子查询实现 exists 功能 */ Criteria criteria = session.createCriteria(VolunteerActivityEntity.class, "activity"); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(VolunteerSignUpEntity.class,"signUp"); detachedCriteria.add(Restrictions.eq("volunteerId", userId)); detachedCriteria.add(Property.forName("activity.activityId").eqProperty("signUp.activityId")); criteria.add(Subqueries.exists(detachedCriteria.setProjection(Projections.property("signUp.signUpId"))));//这里改为notExists就是查询未参加的活动了 if (key != null && !key.equals("")) { //搜索 List list = criteria.add( Restrictions.or( Restrictions.or(Restrictions.like("activityCode", key, MatchMode.ANYWHERE)), Restrictions.or(Restrictions.like("activityTitle", key, MatchMode.ANYWHERE)), Restrictions.or(Restrictions.like("activityContent", key, MatchMode.ANYWHERE)), Restrictions.or(Restrictions.like("activityLeader", key, MatchMode.ANYWHERE)))) .setFirstResult((setPageSize.getCurrPage() - 1) * setPageSize.getPageSize() ) .setMaxResults((setPageSize.getCurrPage() - 1) * setPageSize.getPageSize() + setPageSize.getPageSize()).list(); setPageSize.setRows(list); } else { setPageSize.setRows(criteria.setFirstResult((setPageSize.getCurrPage() - 1) * setPageSize.getPageSize()) .setMaxResults((setPageSize.getCurrPage() - 1) * setPageSize.getPageSize() + setPageSize.getPageSize()).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list()); } session.close(); return setPageSize; } ## 查询结果: ## ![ContractedBlock.gif][] ![ExpandedBlockStart.gif][] Hibernate: select this_.activity_id as activity1_3_0_, this_.activity_code as activity2_3_0_, this_.activity_content as activity3_3_0_, this_.activity_end_time as activity4_3_0_, this_.activity_leader as activity5_3_0_, this_.activity_people_num as activity6_3_0_, this_.activity_sign_end_time as activity7_3_0_, this_.activity_sign_start_time as activity8_3_0_, this_.activity_start_time as activity9_3_0_, this_.activity_title as activit10_3_0_ from volunteer_activity this_ where exists ( select signUp_.sign_up_id as y0_ from volunteer_sign_up signUp_ where signUp_.volunteer_id=? and this_.activity_id=signUp_.activity_id ) limit ? # 二、利用逻辑对象进行多条件查询 # ## 背景: ## > 有一张竞赛表(competition) > > 要求:给一个部门id,查出本部门的竞赛,并模糊参训 ## 代码: ## @Override public PageBean findByDept(Integer deptId, String key, PageBean<CompetitionEntity> pageBean) { Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(CompetitionEntity.class); //TODO 伪外键查询--首要条件 criteria.add(Restrictions.eq("deptId", deptId)); if (key != null && !key.equals("")) { //搜索--实现:where deptId=? and (xxx like ? or xxx like ?...) Disjunction dis = Restrictions.disjunction();//多个or可以拼接 dis.add(Restrictions.like("itemName", key, MatchMode.ANYWHERE)); List list = criteria.add(dis) .setFirstResult((pageBean.getCurrPage() - 1) * pageBean.getPageSize() ) .setMaxResults(pageBean.getPageSize()).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); pageBean.setRows(list); } else { pageBean.setRows( criteria.setFirstResult((pageBean.getCurrPage() - 1) * pageBean.getPageSize()) .setMaxResults(pageBean.getPageSize()).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list()); } pageBean.setTotal(Math.toIntExact((Long) session.createCriteria(CompetitionEntity.class).add(Restrictions.eq("deptId", deptId)) .setProjection(Projections.rowCount()).uniqueResult())); session.close(); return pageBean; } ## 查询结果: ## ![ContractedBlock.gif][] ![ExpandedBlockStart.gif][] Hibernate: select this_.item_id as item_id1_2_0_, this_.awardee as awardee2_2_0_, this_.dept_id as dept_id3_2_0_, this_.dept_name as dept_nam4_2_0_, this_.item_name as item_nam5_2_0_, this_.match_id as match_id6_2_0_, this_.match_name as match_na7_2_0_, this_.prize_grade as prize_gr8_2_0_, this_.prize_img as prize_im9_2_0_, this_.prize_level as prize_l10_2_0_, this_.prize_time as prize_t11_2_0_, this_.teacher_id as teacher12_2_0_, this_.teacher_name as teacher13_2_0_ from competition this_ where this_.dept_id=? and ( this_.item_name like ? ) limit ? # 三、外键查询 # ## 背景: ## > 有一张教师表(sys\_user),与部门表(dept)存在外键约束; > 注: > 生成实体时,可以双向多对一,一个部门对应多个老师,但电脑吃不消 > 也可以用单向一对一,只对教师进行关联,这个最简单,为使用这个 > ![1622529-20190804163055706-880477195.png][] > > > 要求:给一个部门id,查出本部门的竞赛,并模糊参训 ## 代码: ## @Override public PageBean findByDept(Integer deptId, String key, PageBean<TeacherEntity> pageBean) { Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(TeacherEntity.class); Criteria criteriaForCount = session.createCriteria(TeacherEntity.class);//用于获取数据库记录数 //TODO 外键查询 criteria.createAlias("dept", "dept"). add(Restrictions.eq("dept.deptId", deptId)); criteriaForCount.createAlias("dept", "dept"). add(Restrictions.eq("dept.deptId", deptId)); if (key != null && !key.equals("")) { //搜索--实现:where deptId=? and (xxx like ? or xxx like ?...) Disjunction dis = Restrictions.disjunction();//多个or可以拼接 dis.add(Restrictions.like("teacherCode", key, MatchMode.ANYWHERE)); dis.add(Restrictions.like("teacherName", key, MatchMode.ANYWHERE)); List list = criteria.add(dis) .setFirstResult((pageBean.getCurrPage() - 1) * pageBean.getPageSize() ) .setMaxResults(pageBean.getPageSize()).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); pageBean.setRows(list); } else { pageBean.setRows(criteria.setFirstResult((pageBean.getCurrPage() - 1) * pageBean.getPageSize()) .setMaxResults(pageBean.getPageSize()).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list()); } pageBean.setTotal(Math.toIntExact((Long) criteriaForCount.setProjection(Projections.rowCount()).uniqueResult())); session.close(); return pageBean; } 转载于:https://www.cnblogs.com/HuangJie-sol/p/11017895.html [idea_hibernate]: https://www.cnblogs.com/HuangJie-sol/p/10959447.html [1622529-20190804162258012-455446086.png]: /images/20211018/5d4347a81f574b4aa2181c9b10cb976b.png [1622529-20190804162321165-780651703.png]: /images/20211018/3ba2cbd00a6e4dc7b5c1cb80b145ed23.png [1622529-20190804162401283-51449520.png]: /images/20211018/9ed0cf74e990479ca7e20d15b90d3a6c.png [Link 1]: http://zhishichong.com/article/104037 [Link 2]: https://blog.csdn.net/cuiran/article/details/6324083 [ContractedBlock.gif]: https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif [ExpandedBlockStart.gif]: /images/20211018/01d38b9bce45472eb2426a38e39d61d6.png [1622529-20190804163055706-880477195.png]: /images/20211018/7c1356b56f0e4f998c04ccf5bb8bb761.png
相关 「学习笔记」学习笔记合集 可以点击 [https://www.cnblogs.com/hongzy/tag/%E7%AC%94%E8%AE%B0/][https_www.cnblogs.com_hong 淩亂°似流年/ 2023年06月05日 12:48/ 0 赞/ 20 阅读
相关 学习笔记 学习笔记 sudo adduser lilei sudo usermod -G sudo lilei sudo deluse 客官°小女子只卖身不卖艺/ 2022年11月26日 12:58/ 0 赞/ 27 阅读
相关 学习笔记 \ajax: 1、概念:异步的JavaScript 和 xml 1.1异步和同步:客户端和服务器端相互通信的基础上 \客户端必须等待服务器端的响应。在等待的期间客户 深藏阁楼爱情的钟/ 2022年10月29日 13:24/ 0 赞/ 281 阅读
相关 学习笔记 一. CSS 如何实现文字的垂直居中 1. 二.问题记录 1.创建新的JSP页面的时候报错:The superclass “javax.servlet.http.H 超、凢脫俗/ 2022年08月20日 09:30/ 0 赞/ 144 阅读
相关 【学习笔记】git学习笔记 使用git的好处 可以保存每个版本,只要在每个版本做完后进行上传 ![这里写图片描述][70] 可以异地读取更新 爱被打了一巴掌/ 2022年05月14日 09:10/ 0 赞/ 407 阅读
相关 学习笔记 我的第一天学习c\ 1、c\学习网址 [https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide 矫情吗;*/ 2022年05月08日 06:16/ 0 赞/ 326 阅读
相关 学习笔记 测试 ORM JPA EJB JPQL MOM JMS ORM 对象关系映射 英语:Object Relational M 爱被打了一巴掌/ 2022年02月16日 01:57/ 0 赞/ 397 阅读
相关 [笔记] Docker 学习笔记 1. 什么是 Docker > 官方文档:[链接][Link 1],中文文档:[链接][Link 2] Docker 属于 Linux 容器的一种封装,提供简单易用的容 缺乏、安全感/ 2021年11月27日 02:01/ 0 赞/ 591 阅读
相关 学习笔记 1、js如何将136分钟转化为几小时,几分钟 return (Math.floor(minutes/60) + "小时" + (minutes%60) + "分" 爱被打了一巴掌/ 2021年07月25日 23:46/ 0 赞/ 1051 阅读
还没有评论,来说两句吧...