0

如何使用 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?
    }
}
4

1 回答 1

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();
于 2012-08-05T08:16:35.273 回答