【问题标题】:Get Repository for Entity获取实体的存储库
【发布时间】:2019-05-08 08:54:08
【问题描述】:

我有这样的实体:

@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-Method 吗?

【问题讨论】:

  • 为什么不使用依赖注入来获取该实例,例如@Autowired private BookRepository bookRepository;

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


【解决方案1】:

我的建议:直接使用 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?

【讨论】:

  • 非常感谢您的帮助。解决方案非常简单。显然我是一个战利品操蛋:(
  • 如果您对答案感到满意,请考虑接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
相关资源
最近更新 更多