Creating a read-only repository with SpringData

2019-02-04 10:35发布

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

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
}

Thanks!

4条回答
老娘就宠你
2楼-- · 2019-02-04 10:38

As far as we can see in documentation, this is possible by implementing org.springframework.data.repository.Repository.

查看更多
3楼-- · 2019-02-04 10:43

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);
}

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.

查看更多
欢心
4楼-- · 2019-02-04 10:51

For me the following worked. Using Oliver's solution, I was getting error Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findOne found for type while starting up.

@NoRepositoryBean
public interface ReadOnlyRepository<T,ID> extends Repository<T, ID> {
    Optional<T> findById(ID var1);
    boolean existsById(ID var1);
    Iterable<T> findAll();
    Iterable<T> findAllById(Iterable<ID> var1);
    long count();
}
查看更多
你好瞎i
5楼-- · 2019-02-04 10:59

To expand on Oliver Gierke's answer, in the more recent versions of Spring Data you will need the @NoRepositoryBean annotation on your ReadOnlyRepository (parent interface) to prevent application start up errors:

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

@NoRepositoryBean
public interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {

    T findOne(ID id);

    List<T> findAll();

}
查看更多
登录 后发表回答