The find() method of my entityManager from DAO Generica is giving Nullpointer, how to correct?

Asked

Viewed 514 times

1

The change of my DAO is like this:

private EntityManager entityManager;

public void alterar() throws Exception {
    System.out.println("T encontrada");
    System.out.println("iniciando Alterar id: " + this.getId());
    System.out.println("this Class" + this.getClass());
    T encontrada = (T) entityManager.find(this.getClass(), this.getId());
    System.out.println("encontrada");
    try {
        System.out.println("Iniciando a transacao de alteracao");
        EntityManagerControl.transactionBegin(entityManager);
        entityManager.merge(this);
        EntityManagerControl.transactionCommit(entityManager);
    } catch (Exception e) {
        EntityManagerControl.transactionRollback(entityManager);
        e.printStackTrace();
    } finally {
        // manager.close();
    }
}

I have records in the database and I have that record saved in the database but at the moment I declare in the Controller object.change(), it from nullPointer in the find command below:

T encontrada = (T) entityManager.find(this.getClass(), this.getId());

How you fix that mistake?

  • 3

    Hello Thiago, all right? How are you building this Entitymanager? Are you using Vraptor, right? If so, did you use @Inject? Are you using a plugin like vraptor-Hibernate or vraptor-jpa? Give us more details about your below :)

  • @Turini actually, I am not using any plugin of these, it is a Maven project, with vRaptor, Hibernate and JPA 2.0, in the other methods as to insert and remove this similar just not have this find(), are running normal and comes to Entitymanager.

  • Put the method code getId, must be the problem there.

  • @Jéfersonbueno, the getId code(): @Override public Long getId() { return this.id;}

  • but where is this Entitymanager being created, Tiago? You can show us this code?

  • Since Ntity was normal, I changed and created a method to exchange for find ta working for now

Show 1 more comment

1 answer

1


You should inject Entitymanager. An easier way would be with the help of Vraptor himself with the @Inject annotation

public class ProdutoDao {

    @Inject
    private EntityManager manager;

    public void adiciona(Produto produto) {
        manager.persist(produto);
    }
    //...
}

And have somewhere else a @Produces or use the JPA plugin as can be seen in more detail on documentation.

Browser other questions tagged

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