Using Java generics for JPA findAll() query with WHERE clause

前端 未结 4 1257
庸人自扰
庸人自扰 2020-12-14 02:50

So, After a 10+ year break I\'m coming back to Java and trying out stuff with JPA and Java generics. I\'ve created a generics based findAll(other) JPA query tha

相关标签:
4条回答
  • 2020-12-14 03:29

    Hat tip to Adam Bien if you don't want to use createQuery with a String and want type safety:

     @PersistenceContext
     EntityManager em;
    
     public List<ConfigurationEntry> allEntries() {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
            Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
            CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
            TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
            return allQuery.getResultList();
     }
    

    http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as

    0 讨论(0)
  • 2020-12-14 03:29

    I found this page very useful

    https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

    public abstract class GenericDAOWithJPA<T, ID extends Serializable> {
    
        private Class<T> persistentClass;
    
        //This you might want to get injected by the container
        protected EntityManager entityManager;
    
        @SuppressWarnings("unchecked")
        public GenericDAOWithJPA() {
                this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
    
        @SuppressWarnings("unchecked")
        public List<T> findAll() {
                return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
        }
    }
    
    0 讨论(0)
  • 2020-12-14 03:34

    you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with

    entityManager.createNamedQuery(persistentClass.getSimpleName()+"findAll").getResultList();
    
    0 讨论(0)
  • 2020-12-14 03:38

    This will work, and if you need where statement you can add it as parameter.

    class GenericDAOWithJPA<T, ID extends Serializable> {
    

    .......

    public List<T> findAll() {
                return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
        }
    }
    
    0 讨论(0)
提交回复
热议问题