r1949 - in trunk/topia-persistence/src: main/java/org/nuiton/topia/generator main/java/org/nuiton/topia/persistence test/java/org/nuiton/topia/persistence
Author: fdesbois Date: 2010-05-10 15:21:44 +0200 (Mon, 10 May 2010) New Revision: 1949 Url: http://nuiton.org/repositories/revision/topia/1949 Log: - Evo #592 : add exist methods in DAO. CAREFUL !! Rename existNaturalId generated by existByNaturalId. - Reorganize methods order in TopiaDAO and TopiaDAOImpl Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.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 trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java 2010-05-10 13:13:04 UTC (rev 1948) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java 2010-05-10 13:21:44 UTC (rev 1949) @@ -833,9 +833,9 @@ "findByNaturalId", "E", ObjectModelModifier.PUBLIC); addException(findByNaturalId, TopiaException.class); - ObjectModelOperation existNaturalId = addOperation(result, - "existNaturalId", "boolean", ObjectModelModifier.PUBLIC); - addException(existNaturalId, TopiaException.class); + ObjectModelOperation existByNaturalId = addOperation(result, + "existByNaturalId", "boolean", ObjectModelModifier.PUBLIC); + addException(existByNaturalId, TopiaException.class); ObjectModelOperation create = addOperation(result, "create", "E", ObjectModelModifier.PUBLIC); @@ -843,23 +843,23 @@ // used for calling findByProperties in findByNaturalId String searchProperties = ""; - // used for calling findByNaturalId in existNaturalId + // used for calling findByNaturalId in existByNaturalId String params = ""; String clazzName = clazz.getName(); for (ObjectModelAttribute attr : props) { String propName = attr.getName(); // add property as param in both methods addParameter(findByNaturalId, attr.getType(), propName); - addParameter(existNaturalId, attr.getType(), propName); + addParameter(existByNaturalId, attr.getType(), propName); addParameter(create, attr.getType(), propName); searchProperties += ", " + clazzName + '.' + getConstantName(propName) + ", " + propName; - params += ", " + propName; + //params += ", " + propName; } searchProperties = searchProperties.substring(2); - params = params.substring(2); + //params = params.substring(2); setOperationBody(findByNaturalId, "" /*{ @@ -867,9 +867,9 @@ }*/ ); - setOperationBody(existNaturalId, "" + setOperationBody(existByNaturalId, "" /*{ - return findByNaturalId(<%=params%>) != null; + return existByProperties(<%=searchProperties%>); }*/ ); 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-05-10 13:13:04 UTC (rev 1948) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2010-05-10 13:21:44 UTC (rev 1949) @@ -129,6 +129,59 @@ void rollbackTransaction() throws TopiaException; /** + * Find usages of the given {@code entity} in the entities of the given + * {@code type}. + * + * @param type the type of entity to search + * @param entity the entity + * @param <U> tthe type of entity to search + * @return the list of entities of the given type which uses the given + * entity + * @throws TopiaException if any problem while getting data + * @since 2.3.0 + */ + <U extends TopiaEntity> List<U> findUsages(Class<U> type, E entity) + throws TopiaException; + + /** + * Find all usages of the given {@code entity}. + * + * @param entity the entity + * @return the dictionnary of usages of the given entities (keys are entity + * usage container, values are the list of this type of entity to + * use the given entity). + * @throws TopiaException if any pb while getting data + * @since 2.3.0 + */ + + Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) + throws TopiaException; + + /** + * Retourne les permissions a verifier pour l'acces a l'entite pour le + * service Taas. + * + * @param topiaId topiaId d'une entite + * @param actions encoded actions + * @return la liste des permissions + * @throws TopiaException if any pb while getting datas + */ + List<Permission> getRequestPermission(String topiaId, int actions) + throws TopiaException; + + /* Adders */ + + void addTopiaEntityListener(TopiaEntityListener listener); + + void addTopiaEntityVetoable(TopiaEntityVetoable vetoable); + + /* Removers */ + + void removeTopiaEntityListener(TopiaEntityListener listener); + + void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable); + + /** * Construit une nouvelle instance de l'objet géré par ce DAO * * @param properties la liste des propriétés que doit avoir l'objet créé les @@ -183,35 +236,13 @@ */ void delete(E e) throws TopiaException; - E findByTopiaId(String k) throws TopiaException; - - List<E> findAll() throws TopiaException; - /** - * Recuperation de tous les ids en base pour le type d'entite du dao. - * - * @return la liste de tous les ids - * @throws TopiaException si pb en base - */ - List<String> findAllIds() throws TopiaException; - - List<E> findAllWithOrder(String... propertyNames) - throws TopiaException; - - /** - * Compte le nombre d'entites en base - * - * @return le nombre total d'entites existantes - * @throws TopiaException if any pb while getting datas - */ - long size() throws TopiaException; - - /** * Crée une requete basé sur l'entité lié au DAO. Résultat attendu : "FROM * E" * * @return une nouvelle TopiaQuery vide. (uniquement avec le From sur le * type d'entité) + * @since 2.3 */ TopiaQuery createQuery(); @@ -224,10 +255,32 @@ * @param entityAlias alias permettant de manipuler l'entité dans la * requête * @return une nouvelle TopiaQuery + * @since 2.3 */ TopiaQuery createQuery(String entityAlias); + @Deprecated + E findByTopiaId(String k) throws TopiaException; + + E findById(String k) throws TopiaException; + + E findByProperty(String propertyName, Object value) + throws TopiaException; + /** + * @param propertyName le nom de la propriété + * @param value la valeur à tester + * @param others les autres proprietes doivent aller par 2 + * propertyName, value + * @return l'entité trouvé + * @throws TopiaException if any pb while getting datas + */ + E findByProperties(String propertyName, Object value, + Object... others) throws TopiaException; + + E findByProperties(Map<String, Object> properties) throws TopiaException; + + /** * Execute une requête basé sur l'entité du DAO. Permet de récupérer une * entité correspondant à la requête. * @@ -236,10 +289,38 @@ * n'a été trouvée * @throws TopiaException if any pb while getting datas * @see TopiaQuery#executeToEntity(TopiaContext, Class) + * @since 2.3 */ E findByQuery(TopiaQuery query) throws TopiaException; + List<E> findAll() throws TopiaException; + /** + * Recuperation de tous les ids en base pour le type d'entite du dao. + * + * @return la liste de tous les ids + * @throws TopiaException si pb en base + */ + List<String> findAllIds() throws TopiaException; + + List<E> findAllByProperty(String propertyName, Object value) + throws TopiaException; + + /** + * @param propertyName le nom de la propriété + * @param value la valeur à tester + * @param others les autres proprietes doivent aller par 2 + * propertyName, value + * @return l'entité trouvé + * @throws TopiaException if any pb while getting datas + */ + List<E> findAllByProperties(String propertyName, Object value, + Object... others) throws TopiaException; + + List<E> findAllByProperties(Map<String, Object> properties) + 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. * @@ -247,6 +328,7 @@ * @return la liste d'entités correspondant à la recherche * @throws TopiaException if any pb while getting datas * @see TopiaQuery#executeToEntityList(TopiaContext, Class) + * @since 2.3 */ List<E> findAllByQuery(TopiaQuery query) throws TopiaException; @@ -259,6 +341,7 @@ * @return la map d'entités correspondant à la recherche * @throws TopiaException if any pb while getting datas * @see TopiaQuery#executeToEntityMap(TopiaContext, Class) + * @since 2.3 */ Map<String, E> findAllMappedByQuery(TopiaQuery query) throws TopiaException; @@ -274,11 +357,59 @@ * @return la map d'entités correspondant à la recherche * @throws TopiaException if any pb while getting datas * @see TopiaQuery#executeToEntityMap(TopiaContext, Class) + * @since 2.3 */ <K> Map<K, E> findAllMappedByQuery(TopiaQuery query, String keyName, Class<K> keyClass) throws TopiaException; + List<E> findAllWithOrder(String... propertyNames) + throws TopiaException; + /** + * Check the existence of an entity with technical {@code id}. + * + * @param id unique id of the entity to test existence. + * @return true if entity exists, false otherwise + * @throws TopiaException for Topia errors + * @since 2.4 + */ + boolean existById(String id) throws TopiaException; + + /** + * Check the existence of an entity with {@code propertyName} with + * {@code propertyValue}. {@code others} properties can be added to test + * existence. + * + * @param propertyName first property name to test existence + * @param propertyValue first property value to test existence + * @param others altern propertyName and propertyValue + * @return true if entity exists, false otherwise + * @throws TopiaException for Topia errors + * @since 2.4 + */ + boolean existByProperties(String propertyName, Object propertyValue, + Object... others) throws TopiaException; + + + /** + * Check the existence of an entity using a {@code query}. + * + * @param query query used to test existence + * @return true if entity exists, false otherwise + * @throws TopiaException + * @since 2.4 + */ + boolean existByQuery(TopiaQuery query) throws TopiaException; + + /** + * Compte le nombre d'entites en base + * + * @return le nombre total d'entites existantes + * @throws TopiaException if any pb while getting datas + */ + long size() 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. * @@ -299,39 +430,6 @@ */ E findByPrimaryKey(Object... k) throws TopiaException; - E findByProperty(String propertyName, Object value) - throws TopiaException; - - /** - * @param propertyName le nom de la propriété - * @param value la valeur à tester - * @param others les autres proprietes doivent aller par 2 - * propertyName, value - * @return l'entité trouvé - * @throws TopiaException if any pb while getting datas - */ - E findByProperties(String propertyName, Object value, - Object... others) throws TopiaException; - - E findByProperties(Map<String, Object> properties) throws TopiaException; - - List<E> findAllByProperty(String propertyName, Object value) - throws TopiaException; - - /** - * @param propertyName le nom de la propriété - * @param value la valeur à tester - * @param others les autres proprietes doivent aller par 2 - * propertyName, value - * @return l'entité trouvé - * @throws TopiaException if any pb while getting datas - */ - List<E> findAllByProperties(String propertyName, Object value, - Object... others) throws TopiaException; - - List<E> findAllByProperties(Map<String, Object> properties) - throws TopiaException; - /* * Find Contains */ @@ -396,58 +494,5 @@ List<E> findAllContainsProperties(String propertyName, Collection<?> values, Object... others) throws TopiaException; - - /** - * Find usages of the given {@code entity} in the entities of the given - * {@code type}. - * - * @param type the type of entity to search - * @param entity the entity - * @param <U> tthe type of entity to search - * @return the list of entities of the given type which uses the given - * entity - * @throws TopiaException if any problem while getting data - * @since 2.3.0 - */ - <U extends TopiaEntity> List<U> findUsages(Class<U> type, E entity) - throws TopiaException; - - /** - * Find all usages of the given {@code entity}. - * - * @param entity the entity - * @return the dictionnary of usages of the given entities (keys are entity - * usage container, values are the list of this type of entity to - * use the given entity). - * @throws TopiaException if any pb while getting data - * @since 2.3.0 - */ - - Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) - throws TopiaException; - - /** - * Retourne les permissions a verifier pour l'acces a l'entite pour le - * service Taas. - * - * @param topiaId topiaId d'une entite - * @param actions encoded actions - * @return la liste des permissions - * @throws TopiaException if any pb while getting datas - */ - List<Permission> getRequestPermission(String topiaId, int actions) - throws TopiaException; - - /* Adders */ - - void addTopiaEntityListener(TopiaEntityListener listener); - - void addTopiaEntityVetoable(TopiaEntityVetoable vetoable); - - /* Removers */ - - void removeTopiaEntityListener(TopiaEntityListener listener); - - void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable); } //TopiaDAO 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-05-10 13:13:04 UTC (rev 1948) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2010-05-10 13:21:44 UTC (rev 1949) @@ -274,7 +274,94 @@ public void rollbackTransaction() throws TopiaException { } + /** + * private method because this is hibernate specific method and we don't + * want expose it + * + * @return the meta-data of the entity + * @throws TopiaException if any pb + */ + private ClassMetadata getClassMetadata() throws TopiaException { + ClassMetadata meta = getContext().getHibernateFactory() + .getClassMetadata(entityClass); + if (meta == null) { + meta = getContext().getHibernateFactory().getClassMetadata( + entityClass.getName() + "Impl"); + } + return meta; + } + @Override + public <U extends TopiaEntity> List<U> findUsages(Class<U> type, E e) + throws TopiaException { + // must be implemented by specialized dao + throw new UnsupportedOperationException(); + } + + @Override + public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E e) + throws TopiaException { + // must be implemented by specialized dao + throw new UnsupportedOperationException(); + } + + @Override + public List<Permission> getRequestPermission(String topiaId, int actions) + throws TopiaException { + return null; + } + + @Override + public void addTopiaEntityListener(TopiaEntityListener listener) { + getContext().addTopiaEntityListener(entityClass, listener); + } + + @Override + public void addTopiaEntityVetoable(TopiaEntityVetoable vetoable) { + getContext().addTopiaEntityVetoable(entityClass, vetoable); + } + + @Override + public void removeTopiaEntityListener(TopiaEntityListener listener) { + getContext().removeTopiaEntityListener(entityClass, listener); + } + + @Override + public void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable) { + getContext().removeTopiaEntityVetoable(entityClass, vetoable); + } + + /** + * Renvoie la Session contenue dans le contexte + * + * @return hibernate session + * @throws TopiaException if any pb + */ + private Session getSession() throws TopiaException { + return getContext().getHibernate(); + } + + @Override + public E create(E entity) throws TopiaException { + + // TODO EC-20100322 this code may be merged with other create() methods + try { + // first set topiaId + String topiaId = TopiaId.create(entityClass); + TopiaEntityAbstract entityAbstract = (TopiaEntityAbstract) entity; + entityAbstract.setTopiaId(topiaId); + entityAbstract.setTopiaContext(getContext()); + + // save entity + getSession().save(entity); + getContext().getFiresSupport().warnOnUpdateEntity(entity); + return entity; + } catch (HibernateException eee) { + throw new TopiaException(eee); + } + } + + @Override public E create(Object... properties) throws TopiaException { Map<String, Object> map = new HashMap<String, Object>(); Object propertyName = null; @@ -300,107 +387,279 @@ return result; } + /** + * Cette methode appelle fireVetoableCreate et fireOnCreated Si vous la + * surchargé, faites attention a appeler le super ou a appeler vous aussi + * ces deux methodes. + */ @Override - public E findByPrimaryKey(Map<String, Object> keys) - throws TopiaException { + public E create(Map<String, Object> properties) throws TopiaException { + E result = newInstance(); + + // TODO reflechir s'il ne faudrait pas creer l'id avant l'event precedent + // reflechir toujours dans un context on les E pourrait ne pas + // etre des TopiaEntity + if (result instanceof TopiaEntity) { + String topiaId = TopiaId.create(entityClass); + TopiaEntityAbstract entity = (TopiaEntityAbstract) result; + entity.setTopiaId(topiaId); + entity.setTopiaContext(getContext()); + } try { - // we used hibernate meta information for all persistence type - // it's more easy than create different for all persistence - ClassMetadata meta = getClassMetadata(); - if (meta.hasNaturalIdentifier()) { - E result = findByProperties(keys); - return result; + for (Map.Entry<String, Object> e : properties.entrySet()) { + String propertyName = e.getKey(); + Object value = e.getValue(); + PropertyUtils.setProperty(result, propertyName, value); } - } catch (HibernateException eee) { - throw new TopiaException(eee); + } catch (IllegalAccessException eee) { + throw new IllegalArgumentException( + "Can't put properties on new Object", eee); + } catch (InvocationTargetException eee) { + throw new IllegalArgumentException( + "Can't put properties on new Object", eee); + } catch (NoSuchMethodException eee) { + throw new IllegalArgumentException( + "Can't put properties on new Object", eee); } - throw new TopiaException("La classe " + entityClass.getName() - + " n'a pas de cle primaire naturelle"); + // TODO-fdesbois-20100507 : need to be removed for 2.5 version + result.postCreate(); + // on fait un save maintenant, car puisqu'on a creer l'entity au + // travers du DAO, on s'attend a l'avoir a disposition tout de + // suite pour les requetes sans avoir a faire un update dessus + getSession().save(result); + getContext().getFiresSupport().warnOnCreateEntity(result); + return result; } - /** - * private method because this is hibernate specific method and we don't - * want expose it - * - * @return the meta-data of the entity - * @throws TopiaException if any pb - */ - private ClassMetadata getClassMetadata() throws TopiaException { - ClassMetadata meta = getContext().getHibernateFactory() - .getClassMetadata(entityClass); - if (meta == null) { - meta = getContext().getHibernateFactory().getClassMetadata( - entityClass.getName() + "Impl"); + @Override + public E update(E e) throws TopiaException { + try { + getSession().saveOrUpdate(e); + getContext().getFiresSupport().warnOnUpdateEntity(e); + return e; + } catch (HibernateException eee) { + throw new TopiaException(eee); } - return meta; } @Override - public E findByPrimaryKey(Object... k) throws TopiaException { - // TODO pour une meilleur gestion des problemes a la compilation - // mettre un premier couple (propName, value) en argument ca evitera - // de pouvoir appeler cette methode sans argument + public void delete(E e) throws TopiaException { try { - ClassMetadata meta = getClassMetadata(); - if (meta.hasNaturalIdentifier()) { - int[] ikeys = meta.getNaturalIdentifierProperties(); - String[] pnames = meta.getPropertyNames(); - - Map<String, Object> keys = new HashMap<String, Object>(); - for (int ikey : ikeys) { - keys.put(pnames[ikey], k[ikey]); - } - - E result = findByProperties(keys); - return result; - } + getSession().delete(e); + getContext().getFiresSupport().warnOnDeleteEntity(e); } catch (HibernateException eee) { throw new TopiaException(eee); } - throw new TopiaException("La classe " + entityClass.getName() - + " n'a pas de cle primaire naturelle"); + } + @Override + public TopiaQuery createQuery() { + return new TopiaQuery(this); } @Override - public E findByProperties(String propertyName, Object value, - Object... others) throws TopiaException { + public TopiaQuery createQuery(String entityAlias) { + return new TopiaQuery(this, entityAlias); + } + + @Override + public E findByTopiaId(String id) throws TopiaException { + return findById(id); + } + + @Override + public E findById(String id) throws TopiaException { + return findByQuery(createQuery().add(TopiaEntity.ID, id)); + } + + @Override + public E findByProperty(String propertyName, Object value) + throws TopiaException { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(propertyName, value); - Object name = null; - for (int i = 0; i < others.length;) { - try { - name = others[i++]; - value = others[i++]; - properties.put((String) name, value); - } catch (ClassCastException eee) { - throw new IllegalArgumentException( - "Les noms des propriétés doivent être des chaines et " + - "non pas " + propertyName.getClass().getName(), - eee); - } catch (ArrayIndexOutOfBoundsException eee) { - throw new IllegalArgumentException( - "Le nombre d'argument n'est pas un nombre pair: " - + (others.length + 2) - + " La dernière propriété était: " + name, eee); - } - } E result = findByProperties(properties); return result; } @Override + public E findByProperties(String propertyName, Object value, + Object... others) throws TopiaException { +// Map<String, Object> properties = new HashMap<String, Object>(); +// properties.put(propertyName, value); +// Object name = null; +// for (int i = 0; i < others.length;) { +// try { +// name = others[i++]; +// value = others[i++]; +// properties.put((String) name, value); +// } catch (ClassCastException eee) { +// throw new IllegalArgumentException( +// "Les noms des propriétés doivent être des chaines et " + +// "non pas " + propertyName.getClass().getName(), +// eee); +// } catch (ArrayIndexOutOfBoundsException eee) { +// throw new IllegalArgumentException( +// "Le nombre d'argument n'est pas un nombre pair: " +// + (others.length + 2) +// + " La dernière propriété était: " + name, eee); +// } +// } + Map<String, Object> properties = + convertPropertiesArrayToMap(propertyName, value, others); + E result = findByProperties(properties); + return result; + } + + @Override + public E findByProperties(Map<String, Object> properties) + throws TopiaException { + return findByQuery(createQuery().add(properties)); + } + + @Override + public E findByQuery(TopiaQuery query) throws TopiaException { + return query.executeToEntity(context, getEntityClass()); + } + + @Override + public List<E> findAll() throws TopiaException { + return findAllByQuery(createQuery()); + } + + @Override + public List<String> findAllIds() throws TopiaException { + return createQuery().setSelect(TopiaEntity.ID).execute(); + } + + @Override + public List<E> findAllByProperty(String propertyName, Object value) + throws TopiaException { + Map<String, Object> properties = + convertPropertiesArrayToMap(propertyName, value); + List<E> result = findAllByProperties(properties); + return result; + } + + @Override public List<E> findAllByProperties(String propertyName, Object value, Object... others) throws TopiaException { +// Map<String, Object> properties = new HashMap<String, Object>(); +// properties.put(propertyName, value); +// Object name = null; +// for (int i = 0; i < others.length;) { +// try { +// name = others[i++]; +// value = others[i++]; +// properties.put((String) name, value); +// } catch (ClassCastException eee) { +// throw new IllegalArgumentException( +// "Les noms des propriétés doivent être des chaines et " + +// "non pas " + propertyName.getClass().getName(), +// eee); +// } catch (ArrayIndexOutOfBoundsException eee) { +// throw new IllegalArgumentException( +// "Le nombre d'argument n'est pas un nombre pair: " +// + (others.length + 2) +// + " La dernière propriété était: " + name, eee); +// } +// } + Map<String, Object> properties = + convertPropertiesArrayToMap(propertyName, value, others); + List<E> result = findAllByProperties(properties); + return result; + } + + @Override + public List<E> findAllByProperties(Map<String, Object> properties) + throws TopiaException { + return findAllByQuery(createQuery().add(properties)); + } + + @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 { + TopiaQuery query = createQuery().addOrder(propertyNames); + return findAllByQuery(query); + } + + @Override + public boolean existById(String id) throws TopiaException { + boolean result = existByProperties(TopiaEntity.ID, id); + return result; + } + + @Override + public boolean existByProperties(String propertyName, Object propertyValue, + Object... others) throws TopiaException { + Map<String, Object> properties = + convertPropertiesArrayToMap(propertyName, propertyValue, others); + TopiaQuery query = createQuery().add(properties); + boolean result = existByQuery(query); + return result; + } + + @Override + public boolean existByQuery(TopiaQuery query) throws TopiaException { + int count = query.executeCount(); + boolean result = count > 0; + return result; + } + + /** + * Count number of existing entities using {@link + * TopiaQuery#executeCount(TopiaContext)} + * + * @return a long for the number of entities in database + */ + @Override + public long size() throws TopiaException { + return createQuery().executeCount(context); + } + + /** + * Convert a properties array to a proper map used to find entities in + * methods {@link #findByProperties(String, Object, Object...)} and {@link + * #findAllByProperties(String, Object, Object...)}. + * + * @param propertyName first property name to test existence + * @param propertyValue first property value to test existence + * @param others altern propertyName and propertyValue + * @return a Map with properties, propertyName as key. + * @throws IllegalArgumentException for ClassCast or ArrayIndexOutOfBounds + * errors + */ + private Map<String, Object> convertPropertiesArrayToMap(String propertyName, + Object propertyValue, + Object... others) + throws IllegalArgumentException { Map<String, Object> properties = new HashMap<String, Object>(); - properties.put(propertyName, value); + properties.put(propertyName, propertyValue); Object name = null; for (int i = 0; i < others.length;) { try { name = others[i++]; - value = others[i++]; - properties.put((String) name, value); + propertyValue = others[i++]; + properties.put((String) name, propertyValue); } catch (ClassCastException eee) { throw new IllegalArgumentException( "Les noms des propriétés doivent être des chaines et " + @@ -413,11 +672,56 @@ + " La dernière propriété était: " + name, eee); } } - List<E> result = findAllByProperties(properties); - return result; + return properties; } @Override + public E findByPrimaryKey(Map<String, Object> keys) + throws TopiaException { + try { + // we used hibernate meta information for all persistence type + // it's more easy than create different for all persistence + ClassMetadata meta = getClassMetadata(); + if (meta.hasNaturalIdentifier()) { + E result = findByProperties(keys); + return result; + } + } catch (HibernateException eee) { + throw new TopiaException(eee); + } + throw new TopiaException("La classe " + entityClass.getName() + + " n'a pas de cle primaire naturelle"); + + } + + @Override + public E findByPrimaryKey(Object... k) throws TopiaException { + // TODO pour une meilleur gestion des problemes a la compilation + // mettre un premier couple (propName, value) en argument ca evitera + // de pouvoir appeler cette methode sans argument + try { + ClassMetadata meta = getClassMetadata(); + if (meta.hasNaturalIdentifier()) { + int[] ikeys = meta.getNaturalIdentifierProperties(); + String[] pnames = meta.getPropertyNames(); + + Map<String, Object> keys = new HashMap<String, Object>(); + for (int ikey : ikeys) { + keys.put(pnames[ikey], k[ikey]); + } + + E result = findByProperties(keys); + return result; + } + } catch (HibernateException eee) { + throw new TopiaException(eee); + } + throw new TopiaException("La classe " + entityClass.getName() + + " n'a pas de cle primaire naturelle"); + + } + + @Override public E findContainsProperties(Map<String, Collection<?>> properties) throws TopiaException { List<E> results = findAllContainsProperties(properties); @@ -550,359 +854,22 @@ return result; } - @Override - public List<E> findAllByProperty(String propertyName, Object value) - throws TopiaException { - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put(propertyName, value); - List<E> result = findAllByProperties(properties); - return result; - } - - @Override - public E findByProperty(String propertyName, Object value) - throws TopiaException { - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put(propertyName, value); - E result = findByProperties(properties); - return result; - } - - @Override - public <U extends TopiaEntity> List<U> findUsages(Class<U> type, E e) - throws TopiaException { - // must be implemented by specialized dao - throw new UnsupportedOperationException(); - } - - @Override - public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E e) - throws TopiaException { - // must be implemented by specialized dao - throw new UnsupportedOperationException(); - } - - @Override - public void addTopiaEntityListener(TopiaEntityListener listener) { - getContext().addTopiaEntityListener(entityClass, listener); - } - - @Override - public void addTopiaEntityVetoable(TopiaEntityVetoable vetoable) { - getContext().addTopiaEntityVetoable(entityClass, vetoable); - } - - @Override - public void removeTopiaEntityListener(TopiaEntityListener listener) { - getContext().removeTopiaEntityListener(entityClass, listener); - } - - @Override - public void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable) { - getContext().removeTopiaEntityVetoable(entityClass, vetoable); - } - - @Override - public E create(E entity) throws TopiaException { - - // TODO EC-20100322 this code may be merged with other create() methods - try { - // first set topiaId - String topiaId = TopiaId.create(entityClass); - TopiaEntityAbstract entityAbstract = (TopiaEntityAbstract) entity; - entityAbstract.setTopiaId(topiaId); - entityAbstract.setTopiaContext(getContext()); - - // save entity - getSession().save(entity); - getContext().getFiresSupport().warnOnUpdateEntity(entity); - return entity; - } catch (HibernateException eee) { - throw new TopiaException(eee); - } - } - /** - * Cette methode appelle fireVetoableCreate et fireOnCreated Si vous la - * surchargé, faites attention a appeler le super ou a appeler vous aussi - * ces deux methodes. - */ - @Override - public E create(Map<String, Object> properties) throws TopiaException { - E result = newInstance(); - - // TODO reflechir s'il ne faudrait pas creer l'id avant l'event precedent - // reflechir toujours dans un context on les E pourrait ne pas - // etre des TopiaEntity - if (result instanceof TopiaEntity) { - String topiaId = TopiaId.create(entityClass); - TopiaEntityAbstract entity = (TopiaEntityAbstract) result; - entity.setTopiaId(topiaId); - entity.setTopiaContext(getContext()); - } - try { - for (Map.Entry<String, Object> e : properties.entrySet()) { - String propertyName = e.getKey(); - Object value = e.getValue(); - PropertyUtils.setProperty(result, propertyName, value); - } - } catch (IllegalAccessException eee) { - throw new IllegalArgumentException( - "Can't put properties on new Object", eee); - } catch (InvocationTargetException eee) { - throw new IllegalArgumentException( - "Can't put properties on new Object", eee); - } catch (NoSuchMethodException eee) { - throw new IllegalArgumentException( - "Can't put properties on new Object", eee); - } - // TODO-fdesbois-20100507 : need to be removed for 2.5 version - result.postCreate(); - - // on fait un save maintenant, car puisqu'on a creer l'entity au - // travers du DAO, on s'attend a l'avoir a disposition tout de - // suite pour les requetes sans avoir a faire un update dessus - getSession().save(result); - getContext().getFiresSupport().warnOnCreateEntity(result); - return result; - } - - @Override - public E update(E e) throws TopiaException { - try { - getSession().saveOrUpdate(e); - getContext().getFiresSupport().warnOnUpdateEntity(e); - return e; - } catch (HibernateException eee) { - throw new TopiaException(eee); - } - } - - @Override - public void delete(E e) throws TopiaException { - try { - getSession().delete(e); - getContext().getFiresSupport().warnOnDeleteEntity(e); - } catch (HibernateException eee) { - throw new TopiaException(eee); - } - } - - @Override - public E findByTopiaId(String k) throws TopiaException { - return findByQuery(createQuery().add(TopiaEntity.ID, k)); - //return query(Restrictions.idEq(k)); - } - - @Override - public List<E> findAll() throws TopiaException { - return findAllByQuery(createQuery()); - } - - @Override - public List<String> findAllIds() throws TopiaException { - return createQuery().setSelect(TopiaEntity.ID).execute(); - } - - @Override - public TopiaQuery createQuery() { - return new TopiaQuery(this); //TopiaQuery.createQuery(this); - } - - @Override - 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 { -// Criteria criteria = createCriteria(FlushMode.AUTO); -// for (String propertyName : propertyNames) { -// criteria.addOrder(Order.asc(propertyName)); -// } -// List<E> result = (List<E>) criteria.list(); -// result = getContext().getFiresSupport().fireEntitiesLoad(context, -// result); -// return result; -// } catch (HibernateException eee) { -// throw new TopiaException(eee); -// } - - TopiaQuery query = createQuery(); - for (String propertyName : propertyNames) { - query.addOrder(propertyName); - } - return findAllByQuery(query); - } - - /** - * Count number of existing entities using {@link TopiaQuery#executeCount(TopiaContext) - * } FIXME-FD20091224 change type to int like in 2.2.2 version - * - * @return a long for the number of entities in database - */ - @Override - public long size() throws TopiaException { - //int result = findAll().size(); -// List result = this.getContext().find("SELECT count(*) FROM " + getEntityClass().getName() + "Impl"); -// return (Long)result.get(0); - return createQuery().executeCount(context); - } - - @Override - public E findByProperties(Map<String, Object> properties) - throws TopiaException { - //return query(Restrictions.allEq(properties)); - return findByQuery(createQuery().add(properties)); - } - - @Override - public List<E> findAllByProperties(Map<String, Object> properties) - throws TopiaException { - return findAllByQuery(createQuery().add(properties)); - //return queryAll(Restrictions.allEq(properties)); - } - -// private List<E> queryAll(Criterion criterion) throws TopiaException { -// try { -// Criteria criteria = createCriteria(FlushMode.AUTO); -// criteria.add(criterion); -// List<E> result = (List<E>) criteria.list(); -// result = getContext().getFiresSupport().fireEntitiesLoad(context, -// result); -// return result; -// } catch (HibernateException eee) { -// throw new TopiaException(eee); -// } -// } -// -// private E query(Criterion criterion) throws TopiaException { -// try { -// Criteria criteria = createCriteria(FlushMode.AUTO); -// criteria.add(criterion); -// criteria.setMaxResults(1); -// List<E> result = (List<E>) criteria.list(); -// int sizeBefore = (result != null ? result.size() : 0); -// result = getContext().getFiresSupport().fireEntitiesLoad(context, -// result); -// int sizeAfter = (result != null ? result.size() : 0); -// if (sizeAfter < sizeBefore) { -// if (log.isDebugEnabled()) { -// log.debug((sizeBefore - sizeAfter) -// + " element(s) removed. Filter entity: " -// + entityClass.getName() + " - criterion: " -// + criterion); -// } -// } -// if (result != null && result.size() > 0) { -// E elem = result.get(0); -// return elem; -// } -// return null; -// } catch (HibernateException eee) { -// throw new TopiaException(eee); -// } -// } - - //FIXME : Commenté car impossible de trouver le bon Criterion - // ATTENTION ancienne methode du TopiaDAOAbstract deja presente dans le fichier - - // /* (non-Javadoc) - // * @see org.nuiton.topia.persistence.TopiaDAO#findContainsProperties(java.util.Map) - // */ - // public E findContainsProperties(Map<String, Collection> properties) throws TopiaException { - // try { - // Criteria criteria = createCriteria(FlushMode.AUTO); - // for (Entry<String, Collection> entry : properties.entrySet()) { - // for (Object value : entry.getValue()) { - // criteria.add(Restrictions.eq(entry.getKey(), value)); - // } - // } - // criteria.setMaxResults(1); - // List<E> results = (List<E>)criteria.list(); - // if (results.size() > 0) { - // return (E)results.get(0); - // } else { - // return null; - // } - // } catch (HibernateException eee) { - // throw new TopiaException(eee); - // } - // } - // - // /* (non-Javadoc) - // * @see org.nuiton.topia.persistence.TopiaDAO#findAllContainsProperties(java.util.Map) - // */ - // public List<E> findAllContainsProperties(Map<String, Collection> properties) throws TopiaException { - // try { - // Criteria criteria = createCriteria(FlushMode.AUTO); - // for (Entry<String, Collection> entry : properties.entrySet()) { - // for (Object value : entry.getValue()) { - // criteria.add(Restrictions.eq(entry.getKey(), value)); - // } - // } - // List<E> result = (List<E>)criteria.list(); - // return result; - // } catch (HibernateException eee) { - // throw new TopiaException(eee); - // } - // } - - /** * TODO-TC20100225 Should this method deprecated (it is never used ?) * Renvoie un Criteria créé avec l'entityClass * * @param mode le FlushMode du Criteria * @return le Criteria nouvellement créé * @throws TopiaException if any pb + * @deprecated since 2.4 Criteria is no longer used, prefer using {@link + * TopiaQuery} */ + @Deprecated private Criteria createCriteria(FlushMode mode) throws TopiaException { Criteria criteria = getSession().createCriteria(entityClass); criteria.setFlushMode(mode); return criteria; } - /** - * Renvoie la Session contenue dans le contexte - * - * @return hibernate session - * @throws TopiaException if any pb - */ - private Session getSession() throws TopiaException { - return getContext().getHibernate(); - } - @Override - public List<Permission> getRequestPermission(String topiaId, int actions) - throws TopiaException { - return null; - } - - } //TopiaDAOImpl Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2010-05-10 13:13:04 UTC (rev 1948) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2010-05-10 13:21:44 UTC (rev 1949) @@ -181,12 +181,12 @@ NaturalizedEntity.NATURAL_ID_NULL, "str"); transaction.commitTransaction(); - boolean result = dao.existNaturalId(5, "str"); + boolean result = dao.existByNaturalId(5, "str"); Assert.assertTrue(result); // not find with only one correct property - result = dao.existNaturalId(8, "str"); + result = dao.existByNaturalId(8, "str"); Assert.assertFalse(result);
participants (1)
-
fdesbois@users.nuiton.org