Julez
Julez

Reputation: 1050

Getting Entity Class in JPA and Repository Interface

I am applying repository similar to Spring Data JPA where I would only create an interface of an entity repository:

public interface AuthorRepository extends Repository<Author, Long> {
}

I have this also Repository interface:

public interface Repository <T, ID extends Serializable> {
    List<T> findAll() throws Exception;
}

And its implementation, which I find it difficult to get the class name passed in as parameterized (T) to Repository :

public class RepositoryImpl implements Repository {
    @Inject
    private EntityManager em;

    @Override
    public List<Object> findAll() throws Exception {
        try {
            String namedQuery = "SELECT a FROM " + <How do I get the entity here as Author?> + " a";
            TypedQuery<Object> query = em.createNamedQuery(namedQuery, <How do I get the entity class as Author.class?>);

            return query.getResultList();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new ApplicationException();
        }
    }

}

I can't find way how to dynamically generate the entity class (ex. Author) to be created as part of NamedQuery string and an argument for em.createNamequery().

Thanks for any help.

Upvotes: 1

Views: 2400

Answers (2)

Roland S.
Roland S.

Reputation: 71

In the RepositoryImpl you can inject the entityInformation like this:

@Autowired
private JpaEntityInformation<T, ID> entityInformation;

and then use it for example like:

String entityName = entityInformation.getEntityName();

Class<T> entityType = entityInformation.getJavaType();

Custom RepositoryFragments sadly can't autowire the JpaEntityInformation because they are singletons, so for generic fragments one would either need to pass the entity class with each method call and use JpaEntityInformationSupport.getEntityInformation(clazz, entityManager) or modify the BeanDefinition of the fragments and get the clazz using the injection point.

Upvotes: 2

Julez
Julez

Reputation: 1050

Searching world wide web gave me similar approach and codes but none worked but TypeTools works like a charm.

Upvotes: 1

Related Questions