Search in sources :

Example 1 with ClassMetaData

use of org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData in project jaffa-framework by jaffa-projects.

the class JdbcBridge method executeQuery.

/**
 * Executes the query based on the Criteria object.
 * @param criteria The input Criteria.
 * @param dataSource The DataSource against which the query is to be executed.
 * @throws IOException if any error occurs while extracting the String from the criteria.
 * @throws SQLException if any database error occurs.
 * @throws PostLoadFailedException if any error is thrown in the PostLoad trigger of the persistent object.
 * @throws DataSourceCursorRuntimeException if any error occurs while molding the row into the Persistent object.
 * @return a Collection of Persistent objects as a result of the query.
 */
public static Collection executeQuery(Criteria criteria, DataSource dataSource) throws IOException, SQLException, PostLoadFailedException, DataSourceCursorRuntimeException {
    ClassMetaData classMetaData = criteria.getTable() != null ? ConfigurationService.getInstance().getMetaData(criteria.getTable()) : null;
    // The optimization will also be used, if the criteria contains a count(*) for performing an existence-check based on the primary-key
    if (usePreparedStatement(dataSource) && hasPKCriteriaOnly(criteria, classMetaData)) {
        if (criteria.getFunctionEntries() == null || criteria.getFunctionEntries().size() == 0) {
            // Check the cache before executing the query
            IPersistent object = dataSource.lookupObjectCache(criteria);
            if (object != null) {
                if (log.isDebugEnabled())
                    log.debug("Found the cached object: " + object);
                Collection output = new LinkedList();
                output.add(object);
                return output;
            }
            if (log.isDebugEnabled())
                log.debug("Optimized to use the PreparedStatement for querying by primary-key");
            return executeFindByPKWithPreparedStatement(criteria, dataSource, classMetaData);
        } else if (criteria.getFunctionEntries().size() == 1) {
            Criteria.FunctionEntry fe = (Criteria.FunctionEntry) criteria.getFunctionEntries().iterator().next();
            if (fe.getName() == null && fe.getFunction() == Criteria.FUNCTION_COUNT) {
                // Check the cache before executing the query
                IPersistent object = dataSource.lookupObjectCache(criteria);
                if (object != null) {
                    if (log.isDebugEnabled())
                        log.debug("Found the cached object for existence-check by primary-key: " + object);
                    Collection output = new LinkedList();
                    Map map = new HashMap();
                    map.put(fe.getId(), 1);
                    output.add(map);
                    return output;
                }
                if (log.isDebugEnabled())
                    log.debug("Optimized to use the PreparedStatement for existence-check by primary-key");
                return executeExistsWithPreparedStatement(criteria, dataSource, classMetaData);
            }
        }
    }
    // Utilize the pagingPlugin if the Criteria contains values for the firstResult and/or maxResults properties
    IPagingPlugin pagingPlugin = createPagingPlugin(criteria, dataSource.getEngineType());
    if (usePreparedStatement(dataSource)) {
        // Perform a query using a PreparedStatement
        PreparedStatement pstmt = QueryStatementHelper.getPreparedStatement(criteria, dataSource, pagingPlugin);
        return dataSource.executeQuery(pstmt, classMetaData, criteria, (criteria.getLocking() == Criteria.LOCKING_PARANOID ? QUERY_TIMEOUT_FOR_LOCKING : 0), pagingPlugin);
    } else {
        // Perform a query using a regular Statement
        String sql = QueryStatementHelper.getSQL(criteria, dataSource, pagingPlugin);
        return dataSource.executeQuery(sql, classMetaData, criteria, (criteria.getLocking() == Criteria.LOCKING_PARANOID ? QUERY_TIMEOUT_FOR_LOCKING : 0), pagingPlugin);
    }
}
Also used : IPersistent(org.jaffa.persistence.IPersistent) PreparedStatement(java.sql.PreparedStatement) Criteria(org.jaffa.persistence.Criteria) IPagingPlugin(org.jaffa.persistence.engines.jdbcengine.paging.IPagingPlugin) ClassMetaData(org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData)

Example 2 with ClassMetaData

use of org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData in project jaffa-framework by jaffa-projects.

the class JdbcBridge method executeStoredProcedure.

/**
 * Executes the Stored Procedure.
 * @param sp The Stored Procedure to execute.
 * @param criteria The input Criteria.
 * @param dataSource The DataSource against which the Stored Procedure is to be executed.
 * @throws SQLException if any database error occurs.
 * @throws PostLoadFailedException if any error is thrown in the PostLoad trigger of the persistent object.
 * @throws IllegalAccessException if the class is not accessible.
 * @throws InvocationTargetException if the accessor/mutator method for the Stored Procedure throws an exception.
 * @throws IOException if any error occurs in reading the data from the database.
 * @throws InstantiationException if any exception occurs in instantiating an object.
 */
public static void executeStoredProcedure(IStoredProcedure sp, Criteria criteria, DataSource dataSource) throws SQLException, PostLoadFailedException, IllegalAccessException, InvocationTargetException, IOException, InstantiationException {
    // get a CallableStatement
    CallableStatement stmt = dataSource.getCallableStatement(sp.prepareCall());
    String[] parameters = sp.getParameters();
    String[] paramSqlTypes = sp.getParamSqlTypes();
    int[] paramDirections = sp.getParamDirections();
    Class clazz = PersistentInstanceFactory.getActualPersistentClass(sp);
    for (int i = 0; i < parameters.length; i++) {
        // set the input parameters
        if (paramDirections[i] == IStoredProcedure.IN || paramDirections[i] == IStoredProcedure.BOTH) {
            Object value = Introspection.getAccessorMethod(clazz, parameters[i], null).invoke(sp, new Object[0]);
            DataTranslator.setAppObject(stmt, i + 1, value, paramSqlTypes[i], dataSource.getEngineType());
        }
        // register the out parameters
        if (paramDirections[i] == IStoredProcedure.OUT || paramDirections[i] == IStoredProcedure.BOTH) {
            int sqlType = DataTranslator.getSqlType(paramSqlTypes[i], dataSource.getEngineType());
            stmt.registerOutParameter(i + 1, sqlType);
        }
    }
    // execute the stored procedure
    if (log.isInfoEnabled())
        log.info("Executing the Stored Procedure " + clazz.getName() + " with initial state:\n" + ((Object) sp).toString());
    stmt.execute();
    // set the output parameters
    for (int i = 0; i < parameters.length; i++) {
        if (paramDirections[i] == IStoredProcedure.OUT || paramDirections[i] == IStoredProcedure.BOTH) {
            if (IStoredProcedure.CURSOR.equals(paramSqlTypes[i])) {
                Method mutatorMethod = Introspection.getMutatorMethod(clazz, parameters[i], null);
                if (mutatorMethod.getParameterTypes() != null && mutatorMethod.getParameterTypes().length == 1 && mutatorMethod.getParameterTypes()[0].isArray()) {
                    ClassMetaData classMetaData = ConfigurationService.getInstance().getMetaData(mutatorMethod.getParameterTypes()[0].getComponentType().getName());
                    Collection objects = dataSource.loadResultSet(stmt, (ResultSet) stmt.getObject(i + 1), classMetaData, criteria);
                    // Iterate through the collection so that all the objects get loaded
                    for (Iterator itr = objects.iterator(); itr.hasNext(); ) itr.next();
                    // Now convert the collection into an array
                    Object arrayObject = null;
                    if (objects.size() > 0) {
                        int index = 0;
                        arrayObject = Array.newInstance(mutatorMethod.getParameterTypes()[0].getComponentType(), objects.size());
                        for (Iterator itr = objects.iterator(); itr.hasNext(); ) {
                            Array.set(arrayObject, index, itr.next());
                            ++index;
                        }
                    }
                    mutatorMethod.invoke(sp, new Object[] { arrayObject });
                } else {
                    log.warn("Method 'public void set" + parameters[i] + "(Object[] objects)' not found.");
                }
            } else {
                Object value = DataTranslator.getAppObject(stmt, i + 1, paramSqlTypes[i], dataSource.getEngineType());
                Introspection.getMutatorMethod(clazz, parameters[i], null).invoke(sp, new Object[] { value });
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug("Contents of the Stored Procedure " + clazz.getName() + " after execution:\n" + ((Object) sp).toString());
    dataSource.closeStatement(stmt);
}
Also used : CallableStatement(java.sql.CallableStatement) ClassMetaData(org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData)

Example 3 with ClassMetaData

use of org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData in project jaffa-framework by jaffa-projects.

the class StatementHelper method getLockStatementString.

/**
 * Returns a SQL String for use in Statements for locking records in the table corresponding to the input Persistent object.
 * @param object The object to be locked.
 * @param engineType The engine type as defined in init.xml
 * @throws IllegalAccessException if the accessor Method for an attribute enforces Java language access control and the underlying method is inaccessible.
 * @throws InvocationTargetException if the accessor method for an attribute throws an exception.
 * @throws IOException if any error occurs while extracting the value for an attribute.
 * @return a SQL String for use in Statements for locking records.
 */
public static String getLockStatementString(IPersistent object, String engineType) throws IllegalAccessException, InvocationTargetException, IOException {
    ClassMetaData classMetaData = getClassMetaData(object);
    StringBuffer buf = new StringBuffer(SELECT_1_FROM);
    buf.append(' ');
    buf.append(classMetaData.getTable());
    buf.append(' ');
    // Added for supplying Locking 'Hints' used by SqlServer
    buf.append(Variant.getProperty(engineType, Variant.PROP_LOCK_CONSTRUCT_IN_FROM_SELECT_STATEMENT));
    buf.append(' ');
    buf.append(WHERE);
    buf.append(' ');
    boolean first = true;
    for (Iterator i = classMetaData.getAllKeyFieldNames().iterator(); i.hasNext(); ) {
        if (first) {
            first = false;
        } else {
            buf.append(AND);
            buf.append(' ');
        }
        String attributeName = (String) i.next();
        Object value = MoldingService.getInstanceValue(object, classMetaData, attributeName);
        buf.append(formatSqlName(classMetaData.getSqlName(attributeName), engineType));
        if (value == null)
            buf.append(' ').append(IS_NULL);
        else
            buf.append('=').append(DataTranslator.getDml(value, classMetaData.getSqlType(attributeName), engineType));
        buf.append(' ');
    }
    buf.append(Variant.getProperty(engineType, Variant.PROP_LOCK_CONSTRUCT_IN_SELECT_STATEMENT));
    return buf.toString();
}
Also used : Iterator(java.util.Iterator) ClassMetaData(org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData)

Example 4 with ClassMetaData

use of org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData in project jaffa-framework by jaffa-projects.

the class PersistentInstanceInvocationHandler method invokeFieldValidator.

/**
 * Invokes FieldValidator.validate(value, MetaClass.META_FIELD_NAME, true).
 */
private void invokeFieldValidator(String fieldName, Object value, IPersistent persistentObject) throws ValidationException, FrameworkException {
    Class domainClass = PersistentInstanceFactory.getActualPersistentClass(persistentObject);
    try {
        // Determine the datatype for the fieldName from the ClassMetaData
        ClassMetaData classMetaData = ConfigurationService.getInstance().getMetaData(domainClass.getName());
        String type = classMetaData.getType(fieldName);
        Class clazz = type.equals("byte[]") ? byte[].class : Class.forName(type);
        // Determine the FieldMetaData class
        FieldMetaData fieldMetaData = PersistentHelper.getFieldMetaData(domainClass.getName(), fieldName);
        // Get a handle on the method 'public static void validate(Object, FieldMetaData, boolean)' of the FieldValidator class
        Method m = FieldValidator.class.getMethod("validate", new Class[] { clazz, fieldMetaData.getClass(), Boolean.TYPE });
        // Now invoke the method
        m.invoke(null, new Object[] { value, fieldMetaData, Boolean.TRUE });
    } catch (ClassNotFoundException e) {
    // MetaClass doesn't exist. Do nothing
    } catch (NoSuchMethodException e) {
    // Method 'public static FieldMetaData getFieldMetaData(String fieldName)' doesn't exist. Do nothing
    } catch (InvocationTargetException e) {
        if (e.getCause() != null) {
            if (e.getCause() instanceof ValidationException)
                throw (ValidationException) e.getCause();
            else if (e.getCause() instanceof FrameworkException)
                throw (FrameworkException) e.getCause();
        }
        throw new ProxyFieldValidatoRuntimeException("Exception thrown when validating " + fieldName + " having the value " + value, e);
    } catch (Exception e) {
        throw new ProxyFieldValidatoRuntimeException("Exception thrown when validating " + fieldName + " having the value " + value, e);
    }
}
Also used : FrameworkException(org.jaffa.exceptions.FrameworkException) Method(java.lang.reflect.Method) ClassMetaData(org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData) InvocationTargetException(java.lang.reflect.InvocationTargetException) FrameworkException(org.jaffa.exceptions.FrameworkException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 5 with ClassMetaData

use of org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData in project jaffa-framework by jaffa-projects.

the class JdbcBridge method executeUpdateWithPreparedStatement.

private static void executeUpdateWithPreparedStatement(IPersistent object, DataSource dataSource) throws SQLException, IllegalAccessException, InvocationTargetException {
    ClassMetaData classMetaData = ConfigurationService.getInstance().getMetaData(PersistentInstanceFactory.getActualPersistentClass(object).getName());
    String sql = PreparedStatementHelper.getUpdatePreparedStatementString(classMetaData, dataSource.getEngineType());
    PreparedStatement pstmt = dataSource.getPreparedStatement(sql);
    int i = 0;
    for (Iterator itr = classMetaData.getAttributes().iterator(); itr.hasNext(); ) {
        ++i;
        String fieldName = (String) itr.next();
        Object value = MoldingService.getInstanceValue(object, classMetaData, fieldName);
        DataTranslator.setAppObject(pstmt, i, value, classMetaData.getSqlType(fieldName), dataSource.getEngineType());
    }
    for (Iterator itr = classMetaData.getAllKeyFieldNames().iterator(); itr.hasNext(); ) {
        ++i;
        String fieldName = (String) itr.next();
        Object value = MoldingService.getInstanceValue(object, classMetaData, fieldName);
        DataTranslator.setAppObject(pstmt, i, value, classMetaData.getSqlType(fieldName), dataSource.getEngineType());
    }
    dataSource.executeUpdate(pstmt);
}
Also used : PreparedStatement(java.sql.PreparedStatement) ClassMetaData(org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData)

Aggregations

ClassMetaData (org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData)12 PreparedStatement (java.sql.PreparedStatement)5 Iterator (java.util.Iterator)4 Criteria (org.jaffa.persistence.Criteria)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 CallableStatement (java.sql.CallableStatement)1 FrameworkException (org.jaffa.exceptions.FrameworkException)1 AtomicCriteria (org.jaffa.persistence.AtomicCriteria)1 IPersistent (org.jaffa.persistence.IPersistent)1 IPagingPlugin (org.jaffa.persistence.engines.jdbcengine.paging.IPagingPlugin)1