Search code examples
javaspring-bootspring-data-jpaspring-repositories

Get Repository for Entity


I have Entities like:

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

and a Repositories like:

@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);
}

Now I want to get the repository of one Entity to find the Entity by ID. But I don't know how I can get a instance of the e.g. BookRepository. I created the following Methods:

    @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;
}

The field is:

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
}

Can someone help me to fill the getClassRepositoryOfEntity-Method?


Solution

  • My suggestion: use an entityManager directly. You can find an entity of any class.

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

    If you are convinced that you need through spring repository, look at How to retrieve spring data repository instance for given domain class?