2012-08-05 164 views
0

如何與JPQL查詢的加入最大,因爲這個SQL:SELECT MAX(MESSAGENUMBER) FROM ARTICLE left join NEWSGROUP on ARTICLE.NEWSGROUP_ID=NEWSGROUP.ID WHERE NEWSGROUP.newsgroup = "gwene.com.economist";JPQL查詢最大int值的聯接

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? 
    } 
} 

回答

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(); 
+0

您可以給我你對這個JPQL相關問題的意見,https://stackoverflow.com/q/44437322/363573 – Stephan 2017-06-08 16:11:52