使用SpringData创建只读存储库 [英] Creating a read-only repository with SpringData
问题描述
是否可以使用Spring Data创建只读存储库?
Is it possible to create read-only repositories using Spring Data?
我有一些链接到视图的实体,还有一些子实体,我想为其提供一个包含诸如findAll()
,findOne()
之类的方法以及带有@Query
annotation的方法的存储库.我想避免提供像save(…)
和delete(…)
这样的方法,因为它们没有意义,并且可能会产生错误.
I have some entities linked to views and some child entities for which I would like to provide a repository with some methods like findAll()
, findOne()
and some methods with the @Query
annotation. I would like to avoid providing methods like save(…)
and delete(…)
since they make no sense and could create errors.
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
}
谢谢!
推荐答案
是的,方法是添加手工制作的基础存储库.您通常使用这样的内容:
Yes, the way to go is to add a handcrafted base repository. You usually use something like this:
public interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {
T findOne(ID id);
Iterable<T> findAll();
}
您现在可以让您定义刚刚定义的具体回购扩展:
You can now have you concrete repos extend that just defined one:
public interface PersonRepository extends ReadOnlyRepository<Person, Long> {
T findByEmailAddress(String emailAddress);
}
定义基本存储库的关键部分是方法声明与CrudRepository
中声明的方法具有非常相同的签名,如果是这种情况,我们仍然可以将调用路由到实现bean的支持中存储库代理.我写了更详细的博客文章有关该主题的信息,请参见SpringSource博客.
The crucial part defining the base repo is that the method declarations carry the very same signature as the methods declared in CrudRepository
if that's the case we can still route the calls into the implementation bean backing the repository proxy. I've written a more detailed blog post about that topic in the SpringSource blog.
这篇关于使用SpringData创建只读存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!