package net.sourceforge.javautil.database.query.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import net.sourceforge.javautil.database.query.IQueryExecutor;
import net.sourceforge.javautil.database.query.IQueryFragmentCriteriaParameter;
import net.sourceforge.javautil.database.query.QuerySnapshot;
/**
* This will execute a {@link QueryBuilderSelectJPA} based query.
*
* @author elponderador
* @author $Author: ponderator $
* @version $Id: QueryExecutorJPA.java 2286 2010-06-14 04:18:27Z ponderator $
*/
public class QueryExecutorJPA implements IQueryExecutor<QueryBuilderSelectJPA, List<Object>> {
protected EntityManager em;
public QueryExecutorJPA(EntityManager em) {
this.em = em;
}
public List<Object> execute(QueryBuilderSelectJPA builder) {
QuerySnapshot snapshot = builder.build();
String queryString = snapshot.getQueryString();
Query query = em.createQuery(queryString);
if (snapshot.getArguments().size() > 0) {
for (IQueryFragmentCriteriaParameter parameter : snapshot.getArguments()) {
for (String name : parameter.getNamedParameters()) {
if (queryString.contains(":" + name))
query.setParameter(name, builder.getParameters().get(name));
}
}
}
if (builder.getFirstRecord() > -1) query.setFirstResult(builder.getFirstRecord());
if (builder.getMaxRecords() > 0) query.setMaxResults(builder.getMaxRecords());
return query.getResultList();
}
}