获取实体存储库

时间:2019-05-08 08:54:09

标签: java spring-boot spring-data-jpa spring-repositories

我有类似的实体:

@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查找实体。但是我不知道如何获取例如BookRepository。我创建了以下方法:

    @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方法吗?

1 个答案:

答案 0 :(得分:0)

我的建议:直接使用entityManager。您可以找到任何类的实体。

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?