zoukankan      html  css  js  c++  java
  • 项目中遇到的HQL查询问题

    问题描写叙述:
    目的:想要查询出全部最新版本号的组件
    说明:组件:版本号 =1:n关系 ,假设这个组件仅仅有一个版本号也要可以查出来。

    项目中使用的是内存数据库,无法看到表结构,这里的样例仅仅用于模拟。
    也即是:

    1. 最初的数据是这种。
      这里写图片描写叙述
    2. 想要的结果是这种。
      这里写图片描写叙述

    3. 最初的设想是这种。

    select component from Component component where component.owner=:userId andcomponent.componentId.version.versionString
     in (select Max(c.componentId.version.versionString) from Component c where component.owner=:userId  group by c.componentId.name )

    不足:发现对于同一个组件,它的不同版本号都能出现。这个bug我没发现,后来他们发现了。。

    4. 经历的挫折

    select c2.id,c2.name,c2.user,c2.categoryname, Max(c2.version) version from component c2 where  c2.user="tan"  group by c2.name;

    这样在数据库中查询时是没有问题的,关键是在项目中通常是面向对象的,假设在项目中改为例如以下:

    select c.componentId.name,Max(c.componnetId.version.versionString) from component c
    where c.owner=:userId group by c.componentId.name

    发现能正常显示,可是当在前面增加其他字段(比方:c.image)它就会报错了,假设想让它不报错就得以它来分组,可是在实际情况中绝不可能这么做,由于组件同样可是版本号是不同的。

    5. 终于的解决方式
    上面的对象查询中仅仅用一个组件名并不能唯一确定一个相应版本号的组件,那么怎样来唯一确定呢?
    我想了非常久也没有想到解决的方法。后来在我的组长的帮助下,终于攻克了这个问题。



    既然一个字段不能唯一确定,为什么不用2个字段进行唯一确定呢?

    CONCAT(s1,s2) 连接连个字符串 字符串函数 JPQHQL HQL CONCAT([对象属性],[对象属性])

    使用CONCAT函数就行使得组件名和版本号后捆绑在一起。就行唯一确定最新版本号的组件。

    终于解决,代码例如以下:

     select component from Component component where component.owner=:userId and CONCAT(component.componentId.name,component.componentId.version.versionString) 
     in (select CONCAT(c.componentId.name,Max(c.componentId.version.versionString)) from Component c group by c.componentId.name )

    上面的某些情况下会出现bug,比方ComponentName=AB,Version=CD,而另外一个ComponentName=A,Version=BCD,这样一来拼接的结果都是ABCD,这样就会出现反复的问题。

    【怎样解决?】—-可以使用括号括起来分别进行条件的推断

    select component from Component component where component.isApproved=true and component.categoryName = :categoryName and (component.componentId.name,component.componentId.version.versionString) in (select c.componentId.name,Max(c.componentId.version.versionString) from Component c   group by c.componentId.name )

    參考网址:http://www.cnblogs.com/caotang/archive/2011/01/18/1937932.html

    6.反思

    遇到问题,一定要敢于去想,敢于往不同的层面去想并不断的尝试去解决它。切记不可以固执己见。停在原地打转,柳暗花明往往就在于思想越界的一瞬间。

  • 相关阅读:
    动物细胞结构模型 | animal cell structure
    课程学习
    (基因功能 & 基因表达调控)研究方案
    PCR | RT-PCR 的原理及应用
    ggplot的boxplot添加显著性 | Add P-values and Significance Levels to ggplots | 方差分析
    常见的医学基因筛查检测 | genetic testing | 相癌症早筛 | 液体活检
    (转载)RNA表观遗传学开创者何川
    生物信息基本工具和数据库
    女士品茶 | The Lady Tasting Tea | 统计学史
    R Shiny app | 交互式网页开发
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6816925.html
Copyright © 2011-2022 走看看