获取实体的存储库

Get Repository for Entity

我有这样的实体:

@Entity
public class Book  extends AbstractPersistable {
 // some fields
}

和存储库,如:

@Repository
public interface BookRepository extends JpaRepository<Book, Long>, QuerydslPredicateExecutor<Book> {
    Collection<Book> findByAuthorsContains(Author author);

    Collection<Book> findByShelf(Shelf shelf);

    Optional<Book> findByTitle(String title);
}

现在我想获取一个实体的存储库以通过 ID 查找实体。但我不知道如何获得例如书库。我创建了以下方法:

    @Override
public Collection<.datatransfer.graphql.Field> getFieldOfEntity(String entity, Long id) {
    Class<? extends AbstractPersistable> entityClass = getClassesOfTransferDataTypes().stream()
            .filter(aClass -> aClass.getSimpleName().equals(entity))
            .findFirst()
            .orElse(null);
    if (entityClass != null) {
        JpaRepository repository = getClassRepositoryOfEntity(entityClass);
        Object one = repository.getOne(id);
        return createFields(one);
    }
    return null;
}

private JpaRepository getClassRepositoryOfEntity(Class<? extends AbstractPersistable> entityClass) {
    Set<datatransfer.graphql.Field> fields = new HashSet<>();
    // TODO get Repository for entityClass
    return null;
}

private Collection<datatransfer.graphql.Field> createFields(Object o) {
    // TODO transform o in a list of Fields
    return null;
}

字段为:

public class Field {
    public String type;         // String or Integer
    public String fieldName;    // title of field
    public String title;        // annotated Title
    public String value;        // value of entity.field
}

有人可以帮我填写getClassRepositoryOfEntity-方法吗?

我的建议:直接使用entityManager。您可以找到任何 class.

的实体

https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#find-java.lang.Class-java.lang.Object-

如果您确信需要通过 spring 存储库,请查看 How to retrieve spring data repository instance for given domain class?