使用SpringData创建只读存储库

是否可以使用Spring Data创建只读存储库?

我有一些实体链接到视图和一些子实体,我想为其提供一些存储库,其中包含一些方法,如findAll()findOne()和一些带有@Query注释的方法。 我想避免提供像save(…)delete(…)因为它们毫无意义并且可能会产生错误。

 public interface ContactRepository extends JpaRepository, JpaSpecificationExecutor { List findContactByAddress_CityModel_Id(Integer cityId); List findContactByAddress_CityModel_Region_Id(Integer regionId); // ... methods using @Query // no need to save/flush/delete } 

谢谢!

是的,方法是添加手工制作的基础库。 你经常使用这样的东西:

 public interface ReadOnlyRepository extends Repository { T findOne(ID id); Iterable findAll(); } 

您现在可以拥有刚刚定义的具体的repos扩展:

 public interface PersonRepository extends ReadOnlyRepository { T findByEmailAddress(String emailAddress); } 

定义基本存储库的关键部分是方法声明带有与CrudRepository声明的方法完全相同的签名 ,如果是这种情况,我们仍然可以将调用路由到支持存储库代理的实现bean。 我在SpringSource博客上写了一篇关于该主题的更详细的博客文章 。

为了扩展Oliver Gierke的答案,在更新版本的Spring Data中,您需要在ReadOnlyRepository(父接口)上使用@NoRepositoryBean注释来防止应用程序启动错误:

 import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.Repository; @NoRepositoryBean public interface ReadOnlyRepository extends Repository { T findOne(ID id); List findAll(); } 

据我们在文档中可以看到,这可以通过实现org.springframework.data.repository.Repository来实现。

对我来说,以下工作。 使用Oliver的解决方案,我收到错误Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findOne found for type Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findOne found for type启动时Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findOne found for type

 @NoRepositoryBean public interface ReadOnlyRepository extends Repository { Optional findById(ID var1); boolean existsById(ID var1); Iterable findAll(); Iterable findAllById(Iterable var1); long count(); }