Error in the findById of a generic class for persistence and queries using Hibernate JPA

Asked

Viewed 39 times

0

I have a generic class I’m using to perform queries with JPA Hibernate.

My class is like this:

public class BaseRepositoryImpl<T> implements BaseRepository<T>

The problem is that in some methods, such as the findById below, I need to explain the Type of the object. And since it is a generic type, it generates an error.

@Override
public T findById(Long id) {
    em.getTransaction().begin();
    T t = em.find(Class<T>, id);   // ERRORRRR
    em.getTransaction().commit();
    return null;
}

How I must proceed to repair that mistake?

  • 1

    This might help: https://stackoverflow.com/a/9202329

  • It helped a little. But, I had to implement otherwise.

1 answer

0


In the generic class, you need to manually pull the value by instantiating the class.

public BaseRepositoryImpl(Class<T> entity) {
    ...
    this.entity = entity;
}

As it is working with inheritance, the classes that will make the reuse, would be implemented as follows:

public class PessoaRepositoryImpl extends BaseRepositoryImpl<Pessoa> implements PessoaRepository {

    public PessoaRepositoryImpl() {
        super(Pessoa.class);
    }

    ...

}

Inside the constructor, the super is instantiated and we can refer to the class explicitly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.