2017-09-23 65 views
0

我申請資料庫類似於彈簧數據JPA,我只創建一個實體庫的接口:獲取實體類的JPA和倉庫接口

public interface AuthorRepository extends Repository<Author, Long> { 
} 

我這也是庫接口:

public interface Repository <T, ID extends Serializable> { 
    List<T> findAll() throws Exception; 
} 

及其實現,我覺得這是很難得到的類名作爲參數(T)傳遞到倉庫:

public class RepositoryImpl implements Repository { 
    @Inject 
    private EntityManager em; 

    @Override 
    public List<Object> findAll() throws Exception { 
     try { 
      String namedQuery = "SELECT a FROM " + <How do I get the entity here as Author?> + " a"; 
      TypedQuery<Object> query = em.createNamedQuery(namedQuery, <How do I get the entity class as Author.class?>); 

      return query.getResultList(); 
     } catch (Exception e) { 
      System.out.println(e.getMessage()); 
      throw new ApplicationException(); 
     } 
    } 

}

我無法找到如何動態生成實體類的方法(例如, 作者)被創建爲NamedQuery的一部分字符串和的參數em.createNamequery()

感謝您的任何幫助。

+0

可能有用嗎? https://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t –

+0

感謝您的鏈接。我見過很多類似的答案。我甚至按照設計和代碼[這裏](https://developer.jboss.org/wiki/GenericDataAccessObjects),但他們都沒有工作。我總是得到ClassCastException。感謝[TypeTools](https://github.com/jhalterman/typetools)。它像一個魅力。 –

回答

0

搜索萬維網給了我類似的方法和代碼,但沒有工作,但TypeTools工程就像一個魅力。