java—可以用springdata创建一个通用存储库吗?

9njqaruj  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(334)

我想知道怎样才能创建这样一种通用存储库

@Repository
public interface GenericApiDao<T> extends CrudRepository<T, Integer> {

}

不幸的是,我收到了以下错误消息:

> org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'genericApiDao': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object

为什么我们没有权利只在执行时对springdata说类型?
谢谢你的帮助

slmsl1lt

slmsl1lt1#

对您来说,最好的选择是创建自己的界面,而不使用annotation@repository,并将其扩展到不同的存储库:

public interface GenericApiDao<T> extends CrudRepository<T, Integer> {

 Class<?> getClassType();

Optional<T> getObjectByPropertyA(String propertyA);

//your required generic methods for T

}

然后为给定类型创建存储库:

@Repository
@Qualifier("CarRepository")
public interface Car extends GenericApiDao<Car> {

default Class<?> getClassType() {
 return Car.class;
}

//TODO @Query etc
@Override

Optional<Car> getObjectByPropertyA(String propertyA);

}

然后可以创建某种提供者:

@Service
public class RepositoryProvider {

  private List<GenericApiDao<?>> repositories;

  @Autowired
  public RepositoryProvider(List<GenericApiDao<?>> repositories) {
    this.repositories = repositories;
  }

  Optional<GenericApiDao<?>> getRepositoryForType(Class<?> clazz) {
    return repositories.stream.filter(r ->r.getClassType().equals(clazz)).findFirst();
  }
}

warning:i didn不要试图执行它->它只是“在我的脑海中”的一个解决方案
警告2:spring将不允许您使用 @Repository 对于非托管类/实体,如@mhrsalehi所述

相关问题