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