Package com.ctp.cdi.query.builder

Source Code of com.ctp.cdi.query.builder.QueryBuilder

package com.ctp.cdi.query.builder;

import java.text.MessageFormat;
import java.util.List;

import javax.persistence.LockModeType;
import javax.persistence.Query;

import com.ctp.cdi.query.handler.QueryInvocationContext;
import com.ctp.cdi.query.param.Parameters;
import java.lang.reflect.Method;

/**
* Query builder factory. Delegates to concrete implementations.
*
* @author thomashug
*/
public abstract class QueryBuilder {
   
    public static final String QUERY_SELECT = "select e from {0} e";
    public static final String QUERY_COUNT = "select count(e) from {0} e";
    public static final String ENTITY_NAME = "e";
   
    public static String selectQuery(String entityName) {
        return MessageFormat.format(QUERY_SELECT, entityName);
    }
   
    public static String countQuery(String entityName) {
        return MessageFormat.format(QUERY_COUNT, entityName);
    }
   
    public abstract Object execute(QueryInvocationContext ctx) throws Exception;
   
    protected boolean returnsList(Method method) {
        return method.getReturnType().isAssignableFrom(List.class);
    }
   
    protected LockModeType extractLockMode(Method method) {
        Class<com.ctp.cdi.query.Query> query = com.ctp.cdi.query.Query.class;
        if (method.isAnnotationPresent(query) &&
                method.getAnnotation(query).lock() != LockModeType.NONE) {
            return method.getAnnotation(query).lock();
        }
        return null;
    }
   
    protected boolean hasLockMode(Method method) {
        return extractLockMode(method) != null;
    }
   
    protected Query applyRestrictions(QueryInvocationContext context, Query query) {
        Parameters params = context.getParams();
        Method method = context.getMethod();
        if (params.hasSizeRestriction()) {
            query.setMaxResults(params.getSizeRestriciton());
        }
        if (params.hasFirstResult()) {
            query.setFirstResult(params.getFirstResult());
        }
        if (hasLockMode(method)) {
            query.setLockMode(extractLockMode(method));
        }
        return query;
    }
   
}
TOP

Related Classes of com.ctp.cdi.query.builder.QueryBuilder

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.