Hollow.Quincy
Hollow.Quincy

Reputation: 577

CrudRepository OperationNotSupported

I use spring boot 1.2.5.RELEASE. I defined an interface that extends CrudRepository

public interface SampleEntityService extends CrudRepository<SampleEntity, Long> {...}

so my repository would have all methods like: save, delete etc. I would like to disable some methods, for example delete, so it will throw NotSupportedException (or other).

My first idea it to build decorator and override all this methods and throw exception manually.

Is there better solution for this problem ?

Upvotes: 1

Views: 249

Answers (2)

geoand
geoand

Reputation: 64079

Although what you are asking is definitely doable (the solution from @tsachev is totally legit), the cleaner solution would be to define your own custom repository that does only contains the methods you want implemented.

For example you could write:

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

  T findOne(ID id);

  T save(T entity);
}

interface SampleEntityRepository extends SuperSimpleRepository<SampleEntity, Long> {

}

Check out the relevant documentation here

Upvotes: 2

tsachev
tsachev

Reputation: 1171

I assume you want this for Jpa.

One way to achieve this is to use custom JpaRepositoryFactoryBean that adds RepositoryProxyPostProcessor to the JpaRepositoryFactory that disables some methods.

For example:

@Configuration
@EnableJpaRepositories(repositoryFactoryBeanClass = CustomJpaRepositoryFactoryBean.class)
public class MyConfig {

}

And then something like

public class CustomJpaRepositoryFactoryBean extends JpaRepositoryFactoryBean {

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        JpaRepositoryFactory factory = JpaRepositoryFactory(entityManager);
        factory.addRepositoryProxyPostProcessor(new RepositoryProxyPostProcessor() {

            @Override
            public void postProcess(ProxyFactory factory, RepositoryInformation repositoryInformation) {
                factory.addAdvice(new MethodInterceptor() {

                    @Override
                    public Object invoke(MethodInvocation invocation) throws Throwable {
                        if ("unsupportedMethod".equals(invocation.getMethod().getName())) {
                            throw new UnsupportedOperationException();
                        }
                        return invocation.proceed();
                    }
                });
            }
        });
        return factory;
    }
}

Upvotes: 2

Related Questions