JPQL查询连接中列的max int值

时间:2012-08-05 07:51:29

标签: java jpa jpql toplink

如何使用JPQL查询连接的最大值,如此SQL:SELECT MAX(MESSAGENUMBER) FROM ARTICLE left join NEWSGROUP on ARTICLE.NEWSGROUP_ID=NEWSGROUP.ID WHERE NEWSGROUP.newsgroup = "gwene.com.economist";

package net.bounceme.dur.usenet.driver;

import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.Message;
import javax.persistence.*;
import net.bounceme.dur.usenet.model.Article;
import net.bounceme.dur.usenet.model.Newsgroup;

class DatabaseUtils {

    private static final Logger LOG = Logger.getLogger(DatabaseUtils.class.getName());
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("USENETPU");
    private EntityManager em = emf.createEntityManager();

    /*
     * SELECT MAX(MESSAGENUMBER) FROM ARTICLE left join NEWSGROUP on
     * ARTICLE.NEWSGROUP_ID=NEWSGROUP.ID WHERE NEWSGROUP.newsgroup =
     * "gwene.com.economist";
     */
    public int getMax(Folder folder) {
        em.getTransaction().begin();
        int max = 5;
        em.getTransaction().commit();
        return max;
    }

    public void persistArticle(Message message, Folder folder) {
        //do all the persistence here?
        em.getTransaction().begin();
        String fullNewsgroupName = folder.getFullName();
        Newsgroup newsgroup = null;
        TypedQuery<Newsgroup> query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :newsGroupParam", Newsgroup.class);
        query.setParameter("newsGroupParam", fullNewsgroupName);
        try {
            newsgroup = query.getSingleResult();
            LOG.fine("found " + query.getSingleResult());
        } catch (javax.persistence.NoResultException e) {
            LOG.fine(e + "\ncould not find " + fullNewsgroupName); 
            newsgroup = new Newsgroup(folder);
            em.persist(newsgroup);  
        } catch (NonUniqueResultException e) {
            LOG.warning("\nshould never happen\t" + fullNewsgroupName);
        }

        Article article = new Article(message, newsgroup);
        em.persist(article); 
        em.getTransaction().commit();
    }

    public void close() {
        em.close();
        emf.close();//necessary?
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用此类查询获取最大消息编号:

    String queryString = "select max(article.messagenumber) 
from Article article left join Newsgroup newsgroup on article.newsgroup.id=newsgroup.id 
where newsgroup.newsgroup = "gwene.com.economist"

或者您甚至可以在JPQL中简化查询:

String queryString = "select max(article.messagenumber) 
    from Article article left join article.newsgroup newsgroup
    where newsgroup.newsgroup = "gwene.com.economist"

要执行查询,请使用:

int maxNumber = (Integer) entityManager.createQuery(queryString).getSingleResult();