使用 SpringData 创建只读存储库 [英] Creating a read-only repository with SpringData

查看:15
本文介绍了使用 SpringData 创建只读存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to create read-only repositories using Spring Data?

我有一些实体链接到视图和一些子实体,我想为它们提供一个存储库,其中包含一些方法,例如 findAll()findOne() 和一些带有 @Query 注释的方法.我想避免提供像 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 @Queryannotation. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆