Search code examples
javahibernatejpahqljpql

Ordering by some fields in a table without relationship


Hibernate 3.5 JPA 1.0

The annotation @OrderBy is used only for one to many or many to many relationship on the list-field. But I want it to use for the single table, that should be ordered by some fields in a table. It is possible? Or another solution?

for example:

SELECT * FROM INTERCHANGE_KEYS order by PANEL_OPTION, KEY_NAME

I don't want to write hql for each table.


Solution

  • You can create interface for all common actions that you use on JPA entities. This interface must have two generics. I will give you example for 2 actions (persist and findAll) but all others (merge, delete, find, ...) can be implemented, too. For example:

        public interface JpaDaoBase {
           public void persist(E e);
           public List findAll(String orderProperty, OrderType orderType);
        }
    

    E class should be JPA entity and K represents java type of property used for primary key (Long for example).

    And implementation of interface:

    public abstract class JpaDaoBaseImpl implements JpaDaoBase {
    
            protected Class entityClass;
    
            public JpaDaoBaseImpl() {
                this.entityClass = (Class) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
            }
    
            @Override
            public void persist(E e) {
                 entityManager.persist(e);
            }
    
            @Override
            public List findAll(String orderProperty, OrderType orderType) {
            return entityManager.createQuery(
             "select o from " + entityClass.getName() + " o orderby " 
                      orderProperty + + " " + orderType.toString(), entityClass)
             .getResultList();
            }
       }
    

    After that, for entity Example you crate implementation of DAO ExampleDao by extending JpaDaoBaseImpl and you will have this two methods implemented out of the box.

    This is a standard way to create DAO layer in JPA (Hiberante) projects. If you use Spring you can use Spring Data JPA project (they have several standard implementations of Dao layer classes).