项目中遇到的HQL查询问题

来源:互联网 发布:windows phone 微信 编辑:程序博客网 时间:2024/06/06 03:22

问题描述:
目的:想要查询出所有最新版本的组件
说明:组件:版本 =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 cwhere 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.反思

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

1 0
原创粉丝点击