package com.inepex.ineForm.server;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;

import com.google.inject.Provider;

public class CustomDaoCriteriaSelector<ResultType, RootType> {

    public final Provider<EntityManager> em;
    public final CriteriaBuilder cb;
    public final CriteriaQuery<ResultType> cq;
    public final Root<RootType> root;
    public Boolean distinct = null;

    public CustomDaoCriteriaSelector(
        Provider<EntityManager> em,
        Class<ResultType> resultClass,
        Class<RootType> rootClass) {
        this.em = em;
        cb = em.get().getCriteriaBuilder();
        cq = cb.createQuery(resultClass);
        root = cq.from(rootClass);
    }

    public TypedQuery<ResultType> getTypedQuery() {
        return em.get().createQuery(cq);
    }

    public List<ResultType> executeSelect() {
        return getTypedQuery().getResultList();
    }

    public ResultType executeSingleResult() {
        return getTypedQuery().getSingleResult();
    }

    public List<ResultType> executeRangeSelect(int firstResult, int numMaxResult) {
        return getTypedQuery()
            .setFirstResult(firstResult)
            .setMaxResults(numMaxResult)
            .getResultList();
    }

    public void setDistinctIfNotForcedFalse() {
        cq.distinct(distinct == null || distinct);
    }

    /**
     * Should only be called when ResultType is Long
     */
    public Expression<Long> getCountExpression() {
        Path<Long> path = root.get("id");
        return cb.count(path);
    }
}

@@ -391,16 +391,64 @@
 rovider;
+%0Aimport com.google.inject.persist.Transactional;
 %0A%0Apublic
@@ -1101,32 +1101,51 @@
 ery(cq);%0A    %7D%0A%0A
+    @Transactional%0A
     public List%3C
@@ -1170,24 +1170,24 @@
 eSelect() %7B%0A
-
         retu
@@ -1221,32 +1221,51 @@
 tList();%0A    %7D%0A%0A
+    @Transactional%0A
     public Resul
@@ -1343,32 +1343,51 @@
 esult();%0A    %7D%0A%0A
+    @Transactional%0A
     public List%3C

add Transactional annotations