如何合并两个Hibernate查询?

时间:2013-06-21 01:14:39

标签: java hibernate grails hql

我需要合并来自两个不同查询的结果,以便按dateCreated对结果进行排序。

我想这样做:

def query = """ 
  select user from 
   (select v.user, v.dateCreated from Vote as v where v.item=:item order by v.dateCreated desc) as myvotes, 
   (select c.user, c.dateCreated from Comment as c where c.item=:item order by c.dateCreated desc) as mycomments

def item = // some item
tmpUsers = Message.executeQuery (query, [item: item])  

如何合并两个查询?

2 个答案:

答案 0 :(得分:1)

def index() {
        def query1 = """ 
                    select new Map(v.user as user, v.dtCreated as dtCreated) from Vote as v where v.item = :item
                    """
        def query2 = """ 
                    select new Map(c.user as user, c.dtCreated as dtCreated) from Comment as c where c.item = :item
                    """                 

        def result1 = Vote.executeQuery(query1, [item: 'A'])
        def result2 = Comment.executeQuery(query2, [item: 'A'])

        def mergedList = ([] << result1 << result2)?.flatten()?.sort{a,b -> b.dtCreated <=> a.dtCreated}
        render mergedList as grails.converters.JSON
    }

我同意HQL中没有合适的UNION。如果Vote无法与Comment相关联,则上述实施(2个简单查询而不是1个简单查询)将提供预期的结果。

假设,

class Vote {
    String item
    Date dtCreated
    String user
}

class Comment {
    String item
    Date dtCreated
    String user
}

//Bootstrap
def vote1 = new Vote(item: "A", dtCreated: new Date(), user: 'user1')
def vote2 = new Vote(item: "A", dtCreated: new Date() + 1, user: 'user2')
def vote3 = new Vote(item: "A", dtCreated: new Date() + 2, user: 'user3')

def comment1 = new Comment(item: "A", dtCreated: new Date(), user: 'user4')
def comment2 = new Comment(item: "A", dtCreated: new Date() - 4, user: 'user5')
def comment3 = new Comment(item: "A", dtCreated: new Date() - 6, user: 'user6')

[vote1, vote2, vote3, comment1, comment2, comment3]*.save(flush: true, failOnError: true)

//Output Json:
[
    {
        "dtCreated": "2013-06-23T13:49:24Z",
        "user": "user3"
    },
    {
        "dtCreated": "2013-06-22T13:49:24Z",
        "user": "user2"
    },
    {
        "dtCreated": "2013-06-21T13:49:24Z",
        "user": "user4"
    },
    {
        "dtCreated": "2013-06-21T13:49:24Z",
        "user": "user1"
    },
    {
        "dtCreated": "2013-06-17T13:49:24Z",
        "user": "user5"
    },
    {
        "dtCreated": "2013-06-15T13:49:24Z",
        "user": "user6"
    }
]

答案 1 :(得分:0)

你可以使用hibernate-pojo样式来获取Vote和Comment对象的集合并将它们合并到java中。例如:

List<User> mergedUsers = new LinkedList<User>();

List<Vote> votes = voteDAO.getVotes();
List<Comment> comments = commentDAO.getComments();

for(Vote vote : votes) mergedUsers.add(new User(vote));
for(Comment comment : comments) mergedUsers.add(new User(comment));

或者您可以使用SQL“UNION”关键字发出本机jdbc查询,并将结果映射到您的结果对象(用户对象?)