2

I am knocking my head off on a Named Query. I use JPA.. What I would like to achieve is to select all articles with active flags, for a specifc last state (passed as a parameter).

Here are my classes:

  • Article (intId)
  • ArticleState (An article may have one or many states, only only is active though)
  • State (State of an article)

    1. Saved
    2. Draft
    3. Reworked
    4. Approved
    5. Archived
    6. Retired

Here is my query:

@NamedQuery(
    name =  "Article.listArticlesWithActiveFlags",
    query = "SELECT DISTINCT article " +
            "FROM Article article " +
            "INNER JOIN article.articleFlags articleFlag " +
            "INNER JOIN article.articleStates articleState " +
            "WHERE articleFlag.active = true " +
            "AND articleState.state.intId = :intStateId " + 
            "AND articleState.intId = ( " + 
            "      SELECT MAX(articleState2.intId) " +  
            "      FROM Article article2 " + 
            "      INNER JOIN article2.articleStates articleState2 " +  
            "      WHERE articleState2.state.intId = :intStateId " +
            "      AND articleState2.article.intId = article.intId " +
            "      GROUP BY article2.intId) "
),  

The query runs fine without any error. My problem: Let's say I have an article with the following lifecycle:

2012-02-24: created, so it is in "Saved" state 2012-02-25: submitted for approval, so it is now in "Draft" state 2012-02-26: a moderator modifies the articles to meet specific standards, so it is now in "Reworked" state 2012-03-01: the article is now approved for the entire community, so it is now "Approved" 2014-03-01: the article is now archived because it is no longer useful.

So, the article went through all possible states. My requirement is to display two seperate lists: 1. Approved articles with active flags (in case they requires some changes) 2. Archived articles with active flags (in case they are flagged as "still useful")

My problem is that my article shows up in both lists (approved and archived), even if the last state is in fact "Archived".

The named query is called like so: List articlesWithActiveFlags = new ArrayList();

    Query q = em.createNamedQuery("Article.listArticlesWithActiveFlags");
    q.setParameter("intStateId", intStateId);

    articlesWithActiveFlags = q.setMaxResults(intRowLimit).getResultList();

    return articlesWithActiveFlags;

The query is called two times, one for each list. I have verified the parameter using the Eclipse debug mode, and they pass different parameters (4 for approved, and 5 for archived), which is correct.

Any idea?

Thank you

4

1 回答 1

0

使用 @NamedNativeQuery 代替 @NamedQuery 在这里你有一个例子

于 2017-06-17T16:23:23.667 回答