2010-02-16 56 views
3

我跟了一個工作JPA例如檢索類別對象爲這樣:JPQL查詢選擇可選+通用的DAO選擇

return (ArrayList<Category>) getEntityManager().createQuery("from Category").getResultList(); 

的查詢非常速記 - 我找不到什麼是可選的規則什麼不在任何指南中。這種簡潔性是否可以接受?

其次,我想現在這個實現在一個通用的DAO,一些諸如:

public interface DAO<E, K> 
{ 
    List<E> getAll(); 
} 

我怎麼可以重寫第一個查詢到所有類型的工作,我不能在「從分類硬編碼」 ..?

回答

5
  1. 是的,簡潔是可以接受的。儘管我更喜歡完整的語法,因爲它對於擁有更多SQL體驗的其他人更具吸引力。

  2. 你必須一個Class<E>參數添加到您的DAO:

    public List<E> getAll(Class<E> entityClass) { 
        Query query = enittyManager.createQuery("from " + entityClass.getName()); 
        query.getResultList(); 
    } 
    
+0

謝謝你的提示,我得到了一般DAO的構造函數的類名,並使用該變量在查詢! – Mobs 2010-02-16 15:05:05

+0

@Mobs罰款:)順便說一句,接受的答案0 upvotes看起來很奇怪;) – Bozho 2010-02-16 15:06:51

2

你其實不必使用方法參數,但可以使用反射。

Example Code using Reflection

import java.lang.reflect.Field; 
import java.lang.reflect.Modifier; 
import java.lang.reflect.ParameterizedType; 
import java.lang.reflect.Type; 

public class<T> DAO {   
    protected Class<T> clazz; 

    public DAO() 
    { 
     Type genericSuperclass = getClass().getGenericSuperclass(); 
     // Allow this class to be safely instantiated with or without a parameterized type 
     if (genericSuperclass instanceof ParameterizedType) 
     clazz = (Class<T>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0]; 
    } 
}