r1794 - in trunk/topia-persistence/src/main/java/org/nuiton/topia: framework persistence
Author: fdesbois Date: 2010-02-09 01:53:35 +0100 (Tue, 09 Feb 2010) New Revision: 1794 Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java Log: Evo #305 and #306 : Refactor generics in TopiaQuery and use StringBuilder for string concatenation Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java 2010-01-31 17:13:40 UTC (rev 1793) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java 2010-02-09 00:53:35 UTC (rev 1794) @@ -205,7 +205,6 @@ * * Created: 21 déc. 2009 * - * @param <E> The main entity for the query * @author fdesbois * @version $Revision$ * @since 2.3.0 @@ -213,7 +212,7 @@ * Mise a jour: $Date$ * par : $Author$ */ -public class TopiaQuery<E extends TopiaEntity> { +public class TopiaQuery { private static final Log log = LogFactory.getLog(TopiaQuery.class); @@ -221,36 +220,36 @@ protected List<Object> params; /** Select part of the query **/ - protected String select; + protected StringBuilder select; protected boolean distinct; /** From part of the query **/ - protected String from; + protected StringBuilder from; /** Where part of the query **/ - protected String where; + protected StringBuilder where; /** Order By part of the query **/ - protected String orderBy; + protected StringBuilder orderBy; /** Group By part of the query **/ - protected String groupBy; + protected StringBuilder groupBy; protected Integer startIndex; protected Integer endIndex; - /** Used to determine if parentheses are needed for Where input **/ + /** Used to determine if parentheses are needed for Where statement **/ protected boolean parentheses; protected List<String> propertiesToLoad; - protected Class<E> mainEntityClass; + protected Class<? extends TopiaEntity> mainEntityClass; protected String mainAlias; - protected TopiaDAO<E> dao; + protected TopiaDAO<? extends TopiaEntity> dao; /** * Enum to simmplify using operation in query @@ -290,37 +289,153 @@ } } - protected TopiaQuery(Class<E> entityClass) { + public TopiaQuery() { parentheses = true; - mainEntityClass = entityClass; - this.from = " FROM " + mainEntityClass.getName(); } - protected TopiaQuery(TopiaDAO<E> dao) { - this(dao.getEntityClass()); - this.dao = dao; + /** + * Create a TopiaQuery based on the {@code entityClass}. The from statement + * is automatically set. + * + * @param mainEntityClass + */ + protected TopiaQuery(Class<? extends TopiaEntity> mainEntityClass) { + this(); + setFrom(mainEntityClass); } - protected TopiaQuery(Class<E> entityClass, String alias) { - this(entityClass); - this.mainAlias = alias; - this.from += " " + alias; + /** + * Create a TopiaQuery based on the {@code entityClass}. The from statement + * is automatically set, the select statement must be necessary in some + * case, the query will manage this case using the mainAlias by default. + * + * @param mainEntityClass + * @param alias for the mainEntityClass + */ + public TopiaQuery(Class<? extends TopiaEntity> mainEntityClass, String alias) { + this(); + setFrom(mainEntityClass, alias); } - protected TopiaQuery(TopiaDAO<E> dao, String alias) { - this(dao.getEntityClass(), alias); + /** + * Create a TopiaQuery from a DAO. The main entity will be automatically + * added to the select part of the query if it is needed. + * + * @param dao DAO linked to the entity to threat + */ + public TopiaQuery(TopiaDAO<? extends TopiaEntity> dao) { + this(); + setFrom(dao.getEntityClass()); this.dao = dao; } /** + * Create a TopiaQuery from a DAO with an Alias. The main entity will be + * automatically added to the select part of the query if it is needed. + * + * @param dao DAO linked to the entity to threat + * @param alias of the main entity in the query + */ + public TopiaQuery(TopiaDAO<? extends TopiaEntity> dao, String alias) { + this(); + setFrom(dao.getEntityClass(), alias); + this.dao = dao; + } + + /** + * Set the mainEntity in the from part of the query. + * + * @param mainEntityClass type of the mainEntity + * @return the TopiaQuery + */ + public TopiaQuery setFrom(Class<? extends TopiaEntity> mainEntityClass) { + this.mainEntityClass = mainEntityClass; + from = new StringBuilder(" FROM ").append(mainEntityClass.getName()); + return this; + } + + /** + * Set the mainEntity in the from part of the query and use an alias for + * this mainEntity. + * + * @param mainEntityClass type of the mainEntity + * @param alias for the entity in the query + * @return the TopiaQuery + */ + public TopiaQuery setFrom(Class<? extends TopiaEntity> mainEntityClass, String alias) { + setFrom(mainEntityClass); + mainAlias = alias; + from.append(' ').append(alias); + return this; + } + + /** + * Add an element to the from in the query. Used to add some other data in + * the query or for join. + * + * @param str the element to add + * @return the TopiaQuery + */ + public TopiaQuery addFrom(String str) { +// prepareFrom(); + from.append(", ").append(str); + return this; + } + + /** + * Add an other entity type to the from in the query. + * + * @param entityClass different from the mainEntity in the DAO + * @return the TopiaQuery + * @throws TopiaException + */ + public TopiaQuery addFrom(Class<? extends TopiaEntity> entityClass) + throws TopiaException { + return addFrom(entityClass.getName()); + } + + /** + * Add an other entity type to the from in the query with an alias. + * + * @param entityClass different from the mainEntity in the DAO + * @param alias of the entity in the query + * @return the TopiaQuery + * @throws TopiaException + */ + public TopiaQuery addFrom(Class<? extends TopiaEntity> entityClass, String alias) + throws TopiaException { + return addFrom(entityClass.getName() + " " + alias); + } + +// protected void prepareFrom() throws TopiaException { +// if (from == null) { +// if (mainEntityClass != null) { +// if (mainAlias != null) { +// setFrom(mainEntityClass, mainAlias); +// } else { +// setFrom(mainEntityClass); +// } +// } else { +// throw new TopiaException( +// "The query has no FROM statement set, you have to " + +// "instanciate the query using a DAO or manually set the " + +// "FROM statement using setFrom() method"); +// } +// } +// } + + /** * Create a TopiaQuery with entityClass initialization. * * @param <T> entity type extends TopiaEntity * @param entityClass Class for an entity Query * @return the new TopiaQuery + * @deprecated use constructor instead : + * {@link #TopiaQuery(org.nuiton.topia.persistence.TopiaDAO) } */ - public static <T extends TopiaEntity> TopiaQuery<T> createQuery(Class<T> entityClass) { - return new TopiaQuery<T>(entityClass); + @Deprecated + public static <T extends TopiaEntity> TopiaQuery createQuery(Class<T> entityClass) { + return new TopiaQuery(entityClass); } /** @@ -329,9 +444,12 @@ * @param <T> entity type in the dao extends TopiaEntity * @param dao DAO linked to the entity to threat * @return the new TopiaQuery + * @deprecated use constructor instead : + * {@link #TopiaQuery(org.nuiton.topia.persistence.TopiaDAO) } */ - public static <T extends TopiaEntity> TopiaQuery<T> createQuery(TopiaDAO<T> dao) { - return new TopiaQuery<T>(dao); + @Deprecated + public static <T extends TopiaEntity> TopiaQuery createQuery(TopiaDAO<T> dao) { + return new TopiaQuery(dao); } /** @@ -342,9 +460,12 @@ * @param entityClass Class for an entity Query * @param alias of the main entity in the query * @return the new TopiaQuery + * @deprecated use constructor instead : + * {@link #TopiaQuery(java.lang.Class, java.lang.String) } */ - public static <T extends TopiaEntity> TopiaQuery<T> createQuery(Class<T> entityClass, String alias) { - return new TopiaQuery<T>(entityClass, alias); + @Deprecated + public static <T extends TopiaEntity> TopiaQuery createQuery(Class<T> entityClass, String alias) { + return new TopiaQuery(entityClass, alias); } /** @@ -355,14 +476,26 @@ * @param dao DAO linked to the entity to threat * @param alias of the main entity in the query * @return the new TopiaQuery + * @deprecated use constructor instead : + * {@link #TopiaQuery(org.nuiton.topia.persistence.TopiaDAO, String) java.lang.Class) } */ - public static <T extends TopiaEntity> TopiaQuery<T> createQuery(TopiaDAO<T> dao, String alias) { - return new TopiaQuery<T>(dao, alias); + @Deprecated + public static <T extends TopiaEntity> TopiaQuery createQuery(TopiaDAO<T> dao, String alias) { + return new TopiaQuery(dao, alias); } @Override public String toString() { - return fullQuery() + "; (PARAMS : " + getParams() + "); (LIMIT : " + startIndex + ", " + endIndex + ")"; + StringBuilder result = new StringBuilder(fullQuery()). + append("; (PARAMS : "). + append(getParams()). + append("); (LIMIT : "). + append(startIndex). + append(", "). + append(endIndex). + append(')'); + return result.toString(); +// return fullQuery() + "; (PARAMS : " + getParams() + "); (LIMIT : " + startIndex + ", " + endIndex + ")"; } /** @@ -371,26 +504,55 @@ * @return a String corresponding to the full query. */ public String fullQuery() { - String result = ""; - String selectKeyWord = "SELECT "; - selectKeyWord += distinct ? " DISTINCT " : ""; + StringBuilder result = new StringBuilder(); + StringBuilder selectStatement = new StringBuilder("SELECT "); + if (distinct) { + selectStatement.append("DISTINCT "); + } + if (log.isInfoEnabled()) { + log.info("From statement : " + from); + } if (select != null) { - result = selectKeyWord + select; - // Set default select if there is more than one table in from part and main alias is defined - } else if (from.contains(",") && !StringUtils.isEmpty(mainAlias)) { - result = selectKeyWord + mainAlias; + result.append(selectStatement).append(select); + // Set default select if there is more than one table in from + // part and main alias is defined + } else if (StringUtils.contains(from.toString(), ',') && + StringUtils.isNotEmpty(mainAlias)) { + result.append(selectStatement).append(mainAlias); } - result += from; + result.append(from); if (where != null) { - result += where; + result.append(where); } if (groupBy != null) { - result += groupBy; + result.append(groupBy); } if (orderBy != null) { - result += orderBy; + result.append(orderBy); } - return result.trim(); + return StringUtils.trim(result.toString()); + + +// String result = ""; +// String selectKeyWord = "SELECT "; +// selectKeyWord += distinct ? " DISTINCT " : ""; +// if (select != null) { +// result = selectKeyWord + select; +// // Set default select if there is more than one table in from part and main alias is defined +// } else if (from.contains(",") && !StringUtils.isEmpty(mainAlias)) { +// result = selectKeyWord + mainAlias; +// } +// result += from; +// if (where != null) { +// result += where; +// } +// if (groupBy != null) { +// result += groupBy; +// } +// if (orderBy != null) { +// result += orderBy; +// } +// return result.trim(); } /** @@ -400,7 +562,7 @@ * @param paramValue value of the param * @return the TopiaQuery */ - public TopiaQuery<E> addParam(String id, Object paramValue) { + public TopiaQuery addParam(String id, Object paramValue) { getParams().add(id); getParams().add(paramValue); return this; @@ -415,7 +577,7 @@ * @return the TopiaQuery * @see TopiaQuery#getValueName(java.lang.String) */ - public TopiaQuery<E> addParams(List<Object> params) { + public TopiaQuery addParams(List<Object> params) { for (int i = 0; i < params.size(); i += 2) { String paramName = (String)params.get(i); addParam(getValueName(paramName), params.get(i+1)); @@ -457,7 +619,7 @@ * @param properties * @return the TopiaQuery */ - public TopiaQuery<E> addLoad(String... properties) { + public TopiaQuery addLoad(String... properties) { getPropertiesToLoad().addAll(Arrays.asList(properties)); return this; } @@ -476,22 +638,23 @@ * @param where element to add * @return the TopiaQuery */ - public TopiaQuery<E> add(String where) { + public TopiaQuery add(String where) { if (StringUtils.isEmpty(where)) { return this; } if (this.where == null) { - this.where = " WHERE "; + this.where = new StringBuilder(" WHERE "); } else { - this.where += " AND "; + this.where.append(" AND "); } if (parentheses) { - this.where += "("; + this.where.append('('); } - this.where += where; + this.where.append(where); if (parentheses) { - this.where += ")"; + this.where.append(')'); } + // Reinitialize parentheses boolean for next add call parentheses = true; return this; } @@ -509,17 +672,21 @@ * @param paramValue the value of the parameter (an other entity, a String, ...) * @return the TopiaQuery */ - public TopiaQuery<E> add(String paramName, Op constraint, Object paramValue) { + public TopiaQuery add(String paramName, Op constraint, Object paramValue) { + StringBuilder result = new StringBuilder(paramName).append(' '); if (paramValue == null) { - return add(paramName + " " + Op.NULL); + result.append(Op.NULL); + } else { + String valueName = getValueName(paramName); + result.append(constraint).append(" :").append(valueName); + addParam(valueName, paramValue); } - String valueName = getValueName(paramName); parentheses = false; - return add(paramName + " " + constraint + " :" + valueName).addParam(valueName, paramValue); + return add(result.toString()); } protected String getValueName(String paramName) { - int dot = paramName.lastIndexOf("."); + int dot = paramName.lastIndexOf('.'); String valueName = paramName; if (dot != -1) { valueName = paramName.substring(dot+1); @@ -536,8 +703,10 @@ * @param paramName name of the parameter in the query * @return the TopiaQuery */ - public TopiaQuery<E> addNotNull(String paramName) { - return add(paramName + " " + Op.NOT_NULL); + public TopiaQuery addNotNull(String paramName) { + StringBuilder result = + new StringBuilder(paramName).append(' ').append(Op.NOT_NULL); + return add(result.toString()); } /** @@ -550,7 +719,7 @@ * @return the TopiaQuery * @see TopiaQuery#add(String, TopiaQuery.Op, Object) */ - public TopiaQuery<E> add(String paramName, Object paramValue) { + public TopiaQuery add(String paramName, Object paramValue) { return add(paramName, Op.EQ, paramValue); } @@ -562,7 +731,7 @@ * @return the TopiaQuery * @see #add(java.lang.String, java.util.Collection, boolean) */ - public TopiaQuery<E> add(String paramName, Collection<Object> values) { + public TopiaQuery add(String paramName, Collection<Object> values) { return add(paramName, values, false); } @@ -579,27 +748,31 @@ * @return the TopiaQuery * @see #add(java.lang.String) */ - public TopiaQuery<E> add(String paramName, Collection<Object> values, boolean isNull) { - String queryIn = ""; + public TopiaQuery add(String paramName, Collection<Object> values, boolean isNull) { + StringBuilder queryIn = new StringBuilder(); if (!values.isEmpty()) { - queryIn += paramName + " IN ("; + queryIn.append(paramName).append(" IN ("); int count = 1; for (Object value : values) { String valueName = getValueName(paramName + count); if (count != 1) { - queryIn += ", "; + queryIn.append(", "); } - queryIn += ":" + valueName; + queryIn.append(':').append(valueName); addParam(valueName, value); count++; } - queryIn += ")"; + queryIn.append(')'); } if (isNull) { - queryIn += !values.isEmpty() ? " OR " : ""; - queryIn += paramName + " IS NULL"; + if (!values.isEmpty()) { + queryIn.append(" OR "); + } + queryIn.append(paramName).append(' ').append(Op.NULL); + //queryIn += values.isNotEmpty() ? " OR " : ""; + //queryIn += paramName + " IS NULL"; } - return add(queryIn); + return add(queryIn.toString()); } /** @@ -611,7 +784,7 @@ * @param properties * @return the TopiaQuery */ - public TopiaQuery<E> add(Map<String, Object> properties) { + public TopiaQuery add(Map<String, Object> properties) { for (String key : properties.keySet()) { add(key, properties.get(key)); } @@ -619,18 +792,6 @@ } /** - * Add an element to the from in the query. Used to add some other data in - * the query or for join. - * - * @param str the element to add - * @return the TopiaQuery - */ - public TopiaQuery<E> addFrom(String str) { - from += ", " + str; - return this; - } - - /** * Add an element to the select in the query. Depends on the result wanted * in execute methods. The main entity will be automatically added only if * an alias is initialize from constructor. If you want only this select @@ -640,21 +801,22 @@ * @param select element to add * @return the TopiaQuery */ - public TopiaQuery<E> addSelect(String select) { + public TopiaQuery addSelect(String... select) { + String str = convertStringArray(select); // if select is the mainAlias, do nothing - if (mainAlias != null && select.equals(mainAlias)) { + if (mainAlias != null && str.equals(mainAlias)) { return this; } // if select is not null, add the new element to the select if (this.select != null) { - this.select += ", "; + this.select.append(", "); // if mainAlias is not null, add it before adding the select in argument } else if (mainAlias != null) { - this.select = mainAlias + ", "; + this.select = new StringBuilder(mainAlias).append(", "); } else { - this.select = ""; + this.select = new StringBuilder(); } - this.select += select; + this.select.append(convertStringArray(select)); return this; } @@ -665,8 +827,8 @@ * @param select element to set * @return the TopiaQuery */ - public TopiaQuery<E> setSelect(String select) { - this.select = select; + public TopiaQuery setSelect(String... select) { + this.select = new StringBuilder(convertStringArray(select)); return this; } @@ -676,7 +838,7 @@ * * @return the TopiaQuery */ - public TopiaQuery<E> addDistinct() { + public TopiaQuery addDistinct() { this.distinct = true; return this; } @@ -688,17 +850,17 @@ * @param order element to add * @return the TopiaQuery */ - public TopiaQuery<E> addOrder(String order) { + public TopiaQuery addOrder(String... order) { if (orderBy == null) { - orderBy = " ORDER BY "; + orderBy = new StringBuilder(" ORDER BY "); } else { - orderBy += ", "; + orderBy.append(", "); } - orderBy += order; + orderBy.append(convertStringArray(order)); return this; } - public TopiaQuery<E> addOrderDesc(String order) { + public TopiaQuery addOrderDesc(String order) { return addOrder(order + " DESC"); } @@ -709,24 +871,41 @@ * @param group element to add * @return the TopiaQuery */ - public TopiaQuery<E> addGroup(String group) { + public TopiaQuery addGroup(String... group) { if (groupBy == null) { - groupBy = " GROUP BY "; + groupBy = new StringBuilder(" GROUP BY "); } else { - groupBy += ", "; + groupBy.append(", "); } - groupBy += group; + groupBy.append(convertStringArray(group)); return this; } /** + * Helper method for array type. Each value will be separated by a comma. + * @param array of String + * @return a String with values of the array separated by a comma + */ + protected String convertStringArray(String... array) { + StringBuilder result = new StringBuilder(); + for (String value : array) { + result.append(", ").append(value); + } + String str = ""; + if (result.length() > 0) { + str = result.substring(2); + } + return str; + } + + /** * Limit the result of the query with startIndex and endIndex. * * @param start first index to get from the results * @param end last index to get from the results * @return the TopiaQuery */ - public TopiaQuery<E> setLimit(int start, int end) { + public TopiaQuery setLimit(int start, int end) { this.startIndex = start; this.endIndex = end; return this; @@ -736,7 +915,7 @@ * Remove limits previously set * @return the TopiaQuery */ - public TopiaQuery<E> resetLimit() { + public TopiaQuery resetLimit() { startIndex = null; endIndex = null; return this; @@ -748,7 +927,7 @@ * @param max the number of elements wanted * @return the TopiaQuery */ - public TopiaQuery<E> setMaxResults(int max) { + public TopiaQuery setMaxResults(int max) { return setLimit(0,max-1); } @@ -762,14 +941,17 @@ * @see org.nuiton.topia.TopiaContext#find(java.lang.String, java.lang.Object[]) */ public List execute(TopiaContext transaction) throws TopiaException { - if (log.isTraceEnabled()) { - log.trace("# QUERY : " + fullQuery()); - log.trace("# PARAMS : " + Arrays.toString(params.toArray())); - } + // Prepare the From if needed +// prepareFrom(); + String query = fullQuery(); + if (log.isDebugEnabled()) { + log.debug("# QUERY : " + query); + log.debug("# PARAMS : " + Arrays.toString(params.toArray())); + } if (startIndex != null && endIndex != null) { - return transaction.find(fullQuery(), startIndex, endIndex, getParams().toArray()); + return transaction.find(query, startIndex, endIndex, getParams().toArray()); } - return transaction.find(fullQuery(), getParams().toArray()); + return transaction.find(query, getParams().toArray()); } /** @@ -789,12 +971,14 @@ * loaded if they are * prealably set using ${@link #addLoad(java.lang.String[]) }. * + * @param <E> * @param transaction the TopiaContext to use for execution + * @param entityClass * @return a List of TopiaEntity corresponding to the entityClass in argument * @throws TopiaException * @throws ClassCastException */ - public List<E> executeToEntityList(TopiaContext transaction) + public <E extends TopiaEntity> List<E> executeToEntityList(TopiaContext transaction, Class<E> entityClass) throws TopiaException, ClassCastException { List res = execute(transaction); if (log.isTraceEnabled()) { @@ -811,8 +995,8 @@ // We know that the array have at least one element o = ((Object[])o)[0]; } - if (!mainEntityClass.isAssignableFrom(o.getClass())) { - throw new ClassCastException(o.getClass().getName() + " can't be cast to " + mainEntityClass.getName() + " o : " + o); + if (!entityClass.isAssignableFrom(o.getClass())) { + throw new ClassCastException(o.getClass().getName() + " can't be cast to " + entityClass.getName() + " o : " + o); } E entity = (E)o; // Check distinct constraint for complex query where o is firstly an @@ -830,15 +1014,19 @@ /** * DAO must be defined to use this method. * + * @param <E> * @return a List of TopiaEntity corresponding to the entityClass in argument * @throws TopiaException * @throws ClassCastException * @see #executeToEntityList(org.nuiton.topia.TopiaContext) + * @deprecated use dao method instead : + * {@link TopiaDAO#findAllByQuery(TopiaQuery) } */ - public List<E> executeToEntityList() + @Deprecated + public <E extends TopiaEntity> List<E> executeToEntityList() throws TopiaException, ClassCastException { validateDAO(); - return executeToEntityList(dao.getContext()); + return (List<E>)dao.findAllByQuery(this); } /** @@ -846,20 +1034,23 @@ * properties will be loaded if they are * prealably set using ${@link #addLoad(java.lang.String[]) }. * + * @param <E> * @param <K> the type of the map key * @param transaction the TopiaContext to use for execution + * @param entityClass * @param keyName the property name of the key in the entity * @param keyClass the key class for the result map * @return a Map with the key type defined and the entity in value * @throws TopiaException * @throws ClassCastException */ - public <K> Map<K, E> executeToEntityMap(TopiaContext transaction, String keyName, Class<K> keyClass) + public <E extends TopiaEntity, K> Map<K, E> executeToEntityMap(TopiaContext transaction, Class<E> entityClass, String keyName, Class<K> keyClass) throws TopiaException, ClassCastException { // Use LinkedHashMap to keep insert order from list results which can be ordered Map<K, E> results = new LinkedHashMap<K, E>(); - for (E elmt : executeToEntityList(transaction)) { + List<E> list = executeToEntityList(transaction, entityClass); + for (E elmt : list) { Object value = loadProperty(elmt, keyName); if (value != null && !keyClass.isAssignableFrom(value.getClass())) { throw new ClassCastException(value.getClass().getName() + " can't be cast to " + keyClass.getName()); @@ -872,6 +1063,7 @@ /** * DAO must be defined to use this method. * + * @param <E> * @param <K> * @param keyName * @param keyClass @@ -879,11 +1071,14 @@ * @throws TopiaException * @throws ClassCastException * @see #executeToEntityMap(org.nuiton.topia.TopiaContext, java.lang.String, java.lang.Class) + * @deprecated use dao method instead : + * {@link TopiaDAO#findAllMappedByQuery(TopiaQuery, String, Class) } */ - public <K> Map<K, E> executeToEntityMap(String keyName, Class<K> keyClass) + @Deprecated + public <E extends TopiaEntity, K> Map<K, E> executeToEntityMap(String keyName, Class<K> keyClass) throws TopiaException, ClassCastException { validateDAO(); - return executeToEntityMap(dao.getContext(), keyName, keyClass); + return (Map<K, E>)dao.findAllMappedByQuery(this, keyName, keyClass); } /** @@ -891,28 +1086,34 @@ * properties will be loaded if they are * prealably set using ${@link #addLoad(java.lang.String[]) }. * + * @param <E> * @param transaction the TopiaContext to use for execution + * @param entityClass * @return a Map with the key type defined and the entity in value * @throws TopiaException * @throws ClassCastException */ - public Map<String, E> executeToEntityMap(TopiaContext transaction) + public <E extends TopiaEntity> Map<String, E> executeToEntityMap(TopiaContext transaction, Class<E> entityClass) throws TopiaException, ClassCastException { - return executeToEntityMap(transaction, TopiaEntity.TOPIA_ID, String.class); + return executeToEntityMap(transaction, entityClass, TopiaEntity.TOPIA_ID, String.class); } /** * DAO must be defined to use this method. * + * @param <E> * @return a Map with the key type defined and the entity in value * @throws TopiaException * @throws ClassCastException * @see #executeToEntityMap(org.nuiton.topia.TopiaContext) + * @deprecated use dao method instead : + * {@link TopiaDAO#findAllMappedByQuery(TopiaQuery) } */ - public Map<String, E> executeToEntityMap() + @Deprecated + public <E extends TopiaEntity> Map<String, E> executeToEntityMap() throws TopiaException, ClassCastException { validateDAO(); - return executeToEntityMap(dao.getContext()); + return (Map<String, E>)dao.findAllMappedByQuery(this); } /** @@ -920,15 +1121,17 @@ * be loaded if they are * prealably set using ${@link #addLoad(java.lang.String[]) }. * + * @param <E> * @param transaction the TopiaContext to use for execution + * @param entityClass * @return a TopiaEntity corresponding to the entityClass in argument * @throws TopiaException * @throws ClassCastException */ - public E executeToEntity(TopiaContext transaction) + public <E extends TopiaEntity> E executeToEntity(TopiaContext transaction, Class<E> entityClass) throws TopiaException, ClassCastException { setMaxResults(1); - List<E> results = executeToEntityList(transaction); + List<E> results = executeToEntityList(transaction, entityClass); resetLimit(); return !results.isEmpty() ? results.get(0) : null; } @@ -936,23 +1139,53 @@ /** * DAO must be defined to use this method. * + * @param <E> * @return a TopiaEntity corresponding to the entityClass in argument * @throws TopiaException * @throws ClassCastException * @see #executeToEntity(org.nuiton.topia.TopiaContext) + * @deprecated use dao method instead : + * {@link TopiaDAO#findByQuery(TopiaQuery) } */ - public E executeToEntity() + @Deprecated + public <E extends TopiaEntity> E executeToEntity() throws TopiaException, ClassCastException { validateDAO(); - return executeToEntity(dao.getContext()); + //return executeToEntity(dao.getContext()); + return (E)dao.findByQuery(this); } /** - * Execute the query and get an Integer for result. Used for query with - * COUNT or SUM, ... + * Execute the query and get an Object for result. * The select is overriden to get only the right value for return. * * @param transaction the TopiaContext to use for execution + * @param select the Select overriden + * @return an Object + * @throws TopiaException + */ + public Object executeToObject(TopiaContext transaction, String select) throws TopiaException { + StringBuilder oldValue = this.select; + if (!StringUtils.isEmpty(select)) { + setSelect(select); + } + Object result = null; + setMaxResults(1); + List results = execute(transaction); + if (!results.isEmpty()) { + result = results.get(0); + } + this.select = oldValue; + resetLimit(); + return result; + } + + /** + * Execute the query and get an Integer for result. Used only for query with + * aggration select which return a Long : COUNT, SUM ... + * The select is overriden to get only the right value for return. + * + * @param transaction the TopiaContext to use for execution * @param select the Select overriden (ex : SUM(myParam)) * @return an Integer * @throws TopiaException @@ -1003,31 +1236,6 @@ } /** - * Execute the query and get an Object for result. - * The select is overriden to get only the right value for return. - * - * @param transaction the TopiaContext to use for execution - * @param select the Select overriden - * @return an Object - * @throws TopiaException - */ - public Object executeToObject(TopiaContext transaction, String select) throws TopiaException { - String oldValue = this.select; - if (!StringUtils.isEmpty(select)) { - setSelect(select); - } - Object result = null; - setMaxResults(1); - List results = execute(transaction); - if (!results.isEmpty()) { - result = results.get(0); - } - this.select = oldValue; - resetLimit(); - return result; - } - - /** * DAO must be defined to use this method. * * @param select @@ -1066,7 +1274,8 @@ protected boolean validateDAO() throws TopiaException { if (dao == null) { - throw new TopiaException("DAO not defined in TopiaQuery, can't execute it without TopiaContext"); + throw new TopiaException("DAO not defined in TopiaQuery, " + + "can't execute it without TopiaContext"); } return true; } @@ -1143,4 +1352,14 @@ } } + @Override + protected void finalize() { + // Clean StringBuilder statements + select = null; + from = null; + where = null; + orderBy = null; + groupBy = null; + } + } Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2010-01-31 17:13:40 UTC (rev 1793) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2010-02-09 00:53:35 UTC (rev 1794) @@ -150,18 +150,69 @@ * * @return une nouvelle TopiaQuery vide. (uniquement avec le From sur le type d'entité) */ - TopiaQuery<Entity> createQuery(); + TopiaQuery createQuery(); /** - * Crée une requete basé sur l'entité lié au DAO et lui assigne un alias valable dans la requête. + * Crée une requête basé sur l'entité lié au DAO et lui assigne un alias valable dans la requête. * Résultat attendu : "FROM Entity AS entityAlias" * * @param entityAlias alias permettant de manipuler l'entité dans la requête * @return une nouvelle TopiaQuery */ - TopiaQuery<Entity> createQuery(String entityAlias); + TopiaQuery createQuery(String entityAlias); /** + * Execute une requête basé sur l'entité du DAO. Permet de récupérer une + * entité correspondant à la requête. + * + * @param query la requête + * @return l'entité correspondant à la recherche ou null si aucune entité + * n'a été trouvée + * @throws TopiaException + * @see org.nuiton.topia.framework.TopiaQuery#executeToEntity(org.nuiton.topia.TopiaContext, java.lang.Class) + */ + Entity findByQuery(TopiaQuery query) throws TopiaException; + + /** + * Execute une requête basé sur l'entité du DAO. Permet de récupérer une + * liste d'entités correspondant à la requête. + * + * @param query la requête + * @return la liste d'entités correspondant à la recherche + * @throws TopiaException + * @see org.nuiton.topia.framework.TopiaQuery#executeToEntityList(org.nuiton.topia.TopiaContext, java.lang.Class) + */ + List<Entity> findAllByQuery(TopiaQuery query) throws TopiaException; + + /** + * Execute une requête basé sur l'entité du DAO. Permet de récupérer une + * map d'entités correspondant à la requête. La clé de la map étant le + * topiaId de l'entité. + * + * @param query la requête + * @return la map d'entités correspondant à la recherche + * @throws TopiaException + * @see org.nuiton.topia.framework.TopiaQuery#executeToEntityMap(org.nuiton.topia.TopiaContext, java.lang.Class) + */ + Map<String, Entity> findAllMappedByQuery(TopiaQuery query) throws TopiaException; + + /** + * Execute une requête basé sur l'entité du DAO. Permet de récupérer une + * map d'entités correspondant à la requête. Le type et le nom de la + * propriété utilisé comme clé de la map doit être passé en argument. + * + * @param <K> type de la clé de la map + * @param query la requête + * @param keyName nom de la propriété de l'entité utilisée comme clé + * @param keyClass type de la propriété de l'entité utilisée comme clé + * @return la map d'entités correspondant à la recherche + * @throws TopiaException + * @see org.nuiton.topia.framework.TopiaQuery#executeToEntityMap(org.nuiton.topia.TopiaContext, java.lang.Class) + */ + <K> Map<K, Entity> findAllMappedByQuery(TopiaQuery query, + String keyName, Class<K> keyClass) throws TopiaException; + + /** * Recherche la classe en utilisant la cle naturelle, chaque champs de la * cle naturelle est une entre de la map passe en argument. * Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2010-01-31 17:13:40 UTC (rev 1793) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2010-02-09 00:53:35 UTC (rev 1794) @@ -689,7 +689,7 @@ @Override public E findByTopiaId(String k) throws TopiaException { - return createQuery().add(TopiaEntity.TOPIA_ID, k).executeToEntity(); + return findByQuery(createQuery().add(TopiaEntity.TOPIA_ID, k)); //return query(Restrictions.idEq(k)); } @@ -704,27 +704,48 @@ // } catch (HibernateException eee) { // throw new TopiaException(eee); // } - return createQuery().executeToEntityList(); + return findAllByQuery(createQuery()); } @Override public List<String> findAllIds() throws TopiaException { //List<String> find = context.find("select src.topiaId from " + entityClass.getSimpleName() + "Impl src"); //return find; - return createQuery().setSelect(TopiaEntity.TOPIA_ID).execute(context); + return createQuery().setSelect(TopiaEntity.TOPIA_ID).execute(); } @Override - public TopiaQuery<E> createQuery() { - return TopiaQuery.createQuery(this); + public TopiaQuery createQuery() { + return new TopiaQuery(this); //TopiaQuery.createQuery(this); } @Override - public TopiaQuery<E> createQuery(String entityAlias) { - return TopiaQuery.createQuery(this, entityAlias); + public TopiaQuery createQuery(String entityAlias) { + return new TopiaQuery(this, entityAlias); //TopiaQuery.createQuery(this, entityAlias); } @Override + public E findByQuery(TopiaQuery query) throws TopiaException { + return query.executeToEntity(context, getEntityClass()); + } + + @Override + public List<E> findAllByQuery(TopiaQuery query) throws TopiaException { + return query.executeToEntityList(context, getEntityClass()); + } + + @Override + public Map<String, E> findAllMappedByQuery(TopiaQuery query) throws TopiaException { + return query.executeToEntityMap(context, getEntityClass()); + } + + @Override + public <K> Map<K, E> findAllMappedByQuery(TopiaQuery query, String keyName, Class<K> keyClass) + throws TopiaException { + return query.executeToEntityMap(context, getEntityClass(), keyName, keyClass); + } + + @Override public List<E> findAllWithOrder(String... propertyNames) throws TopiaException { // try { @@ -740,11 +761,11 @@ // throw new TopiaException(eee); // } - TopiaQuery<E> query = createQuery(); + TopiaQuery query = createQuery(); for (String propertyName : propertyNames) { query.addOrder(propertyName); } - return query.executeToEntityList(); + return findAllByQuery(query); } /** @@ -765,13 +786,13 @@ public E findByProperties(Map<String, Object> properties) throws TopiaException { //return query(Restrictions.allEq(properties)); - return createQuery().add(properties).executeToEntity(); + return findByQuery(createQuery().add(properties)); } @Override public List<E> findAllByProperties(Map<String, Object> properties) throws TopiaException { - return createQuery().add(properties).executeToEntityList(); + return findAllByQuery(createQuery().add(properties)); //return queryAll(Restrictions.allEq(properties)); }
participants (1)
-
fdesbois@users.nuiton.org