package com.commafeed.backend.dao;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.hibernate.SessionFactory;

import com.commafeed.backend.model.FeedEntryContent;
import com.commafeed.backend.model.QFeedEntry;
import com.commafeed.backend.model.QFeedEntryContent;
import com.google.common.collect.Iterables;

@Singleton
public class FeedEntryContentDAO extends GenericDAO<FeedEntryContent> {

	private QFeedEntryContent content = QFeedEntryContent.feedEntryContent;

	@Inject
	public FeedEntryContentDAO(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	public Long findExisting(String contentHash, String titleHash) {
		List<Long> list = newQuery().from(content).where(content.contentHash.eq(contentHash), content.titleHash.eq(titleHash)).limit(1)
				.list(content.id);
		return Iterables.getFirst(list, null);
	}

	public int deleteWithoutEntries(int max) {
		QFeedEntry entry = QFeedEntry.feedEntry;
		List<FeedEntryContent> list = newQuery().from(content).leftJoin(content.entries, entry).where(entry.id.isNull()).limit(max)
				.list(content);
		int deleted = list.size();
		delete(list);
		return deleted;
	}
}

@@ -361,16 +361,74 @@
 rables;%0D
+%0Aimport com.mysema.query.jpa.hibernate.HibernateSubQuery;%0D
 %0A%0D%0A@Sing
@@ -1052,119 +1052,199 @@
 y;%0D%0A
-%09%09List%3CFeedEntryContent%3E list = newQuery().from(content).leftJoin(content.entries, entry).where(entry.id.isNull
+%0D%0A%09%09HibernateSubQuery subQuery = new HibernateSubQuery().from(entry).where(entry.content.id.eq(content.id));%0D%0A%09%09List%3CFeedEntryContent%3E list = newQuery().from(content).where(subQuery.notExists
 ()).
@@ -1253,22 +1253,16 @@
 mit(max)
-%0D%0A%09%09%09%09
 .list(co
@@ -1270,16 +1270,18 @@
 tent);%0D%0A
+%0D%0A
 %09%09int de

rewrite query using not exists