使用SpringData创建只读存储库
问题内容:
是否可以使用Spring Data创建只读存储库?
我有一些链接到视图的实体,还有一些子实体,我想为其提供一个存储库,其中包含的某些方法findAll()
,findOne()
以及带有@Query
批注的某些方法。我想避免提供像save(…)
和这样的方法,delete(…)
因为它们没有意义,并且可能会产生错误。
public interface ContactRepository extends JpaRepository<ContactModel, Integer>, JpaSpecificationExecutor<ContactModel> {
List<ContactModel> findContactByAddress_CityModel_Id(Integer cityId);
List<ContactModel> findContactByAddress_CityModel_Region_Id(Integer regionId);
// ... methods using @Query
// no need to save/flush/delete
}
谢谢!
问题答案:
是的,方法是添加手工制作的基础存储库。您通常使用以下内容:
public interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {
T findOne(ID id);
Iterable<T> findAll();
}
现在,您可以使刚刚定义的具体回购扩展:
public interface PersonRepository extends ReadOnlyRepository<Person, Long> {
T findByEmailAddress(String emailAddress);
}
定义基本存储库的关键部分是,方法声明 与 声明的方法 具有相同的签名
,在CrudRepository
这种情况下,我们仍然可以将调用路由到支持存储库代理的实现Bean中。我在SpringSource博客中写了一篇关于该主题的更详细的博客文章。