2017-07-30 220 views
2

我使用Spring啓動,當我想擴展SimpleJpaRepository這樣的接口:擴展SimpleJpaRepository

public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>{} 

實施這一項目:

public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID> 
{ 
    private final EntityManager entityManager; 

    public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) 
    { 
     super(domainClass, entityManager); 
     this.entityManager = entityManager; 
    } 
} 

我得到了以下錯誤:

Could not autowire. No beans of 'Class<T>' type found. 

我該如何解決?

+0

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-behaviour-for-all-repositories –

+1

你不應該寫*類*實現'JpaRepository'。 相反,你應該編寫一個擴展'JpaRepository'的*接口*,並且Spring將自動生成一個實現類。 您可以在[Spring Data JPA入門]中找到示例(https://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/)。 –

+0

@ThomasFritsch,我想寫一些類似於https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html的第1.3.2節 –

回答

0

使延長JpaRepository

對於如界面 -

public interface Repository extends JpaRepository<Entity,Integer>,RepositoryCustom // this is our custom repository{ 


} 

資源庫自定義一個接口

public interface RepositoryCustom { 


    List<Entity> getAll(); // define the method signature here 


} 

實現自定義接口

@Transactional 
public class RepositoryImpl implements RepositoryCustom{ 

    @PersistenceContext // this will inject em in your class 
    private EntityManager entityManager; 

    write the method body and return 

} 

Keep in mind the Repository naming convention . If the Interface name is Repository . then the custom interface shuld be named as Repository and the implementation as Repository

+0

謝謝,但這是「將自定義行爲添加到單個存儲庫」(https://docs.spring.io/spring-data/data-commons/docs/1.6的第1.3.1節)。 1.RELEASE/reference/html/repositories.html),我想實現「向所有存儲庫添加自定義行爲」(上述URL的第1.3.2節) –