vendredi 12 février 2016

FindByExample in JPQL

I have decided to write a general findByExample method in my abstract DAO.

my result is :

public List<T> findByExample(T example) throws DAOException {
    try {
        Object object = example;
        String query = "SELECT e from " + object.getClass().getName() + " e where 1 = 1";
        for (Field field : object.getClass().getDeclaredFields()) {
            Object fieldValue;
            field.setAccessible(true);
            if (field.get(object) instanceof List || (java.lang.reflect.Modifier.isStatic(field.getModifiers()))) {
                continue;
            } else {
                fieldValue = field.get(object);
                if (fieldValue != null) {
                    if((fieldValue instanceof String) && !((String)fieldValue).isEmpty())
                    {
                        query += " and e." + field.getName() + " LIKE :" + field.getName();
                    }
                    else
                        query += " and e." + field.getName() + " = :" + field.getName();
                }
            }
        }

        Query q = em.createQuery(query, object.getClass());

        for (Field field : object.getClass().getDeclaredFields()) {
            Object fieldValue;
            field.setAccessible(true);
            if (field.get(object) instanceof List || (java.lang.reflect.Modifier.isStatic(field.getModifiers()))) {
                continue;
            } else {
                fieldValue = field.get(object);
                if (fieldValue != null) {
                    if((fieldValue instanceof String) && !((String)fieldValue).isEmpty())
                    {
                        q.setParameter(field.getName(), "%" + field.get(object) + "%");
                    }
                    else
                        q.setParameter(field.getName(), field.get(object));
                }
            }
        }
        return q.getResultList();

    } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {

        throw new DAOException("", e);
    }
}

I have written it with these Assumptions :

  1. My query will search bidirectional String like search for my String fields
  2. All declared fields of my entity are valid for my query.

How do you think about this piece of code? any better experience? Also please tell me if you see any bug or something like that.





Aucun commentaire:

Enregistrer un commentaire