2

It is possible to inject entity manager (or its factory) into jsf managed bean using @PersistenceContext (or @PersistenceUnit)?

I Tried it but nothing, I obtain a NullPointerException.

zellus
  • 9,617
  • 5
  • 39
  • 56
Alf
  • 2,291
  • 1
  • 28
  • 34

1 Answers1

8

Yes it is possible. This is the syntax.

@PersistenceContext
EntityManager em;

You need to have a persistence.xml in your project. Btw: I'm running Glassfish 3.

After this you can then use methods like em.createNamedQuery.

Also remember the injection takes place after the constructor so if your trying to do database functions in the constructor this will not work. You will have to add the @PostConstruct annotation to a method. This is probably the problem your having.

Drew H
  • 4,699
  • 9
  • 57
  • 90
  • 2
    Note that the EntityManager won't use container-managed transactions (CMT) if injected into a JSF managed bean. Until Java EE 7, only EJBs used container-managed transactions, and Java EE 7 extended CMT only to CDI beans, not to the deprecated JSF managed beans. In other words, if there is an error, the transaction won't be rolled-back by the container: you will have to manage that yourself. [Reference](http://stackoverflow.com/a/17842796/201891) and [reference](https://stackoverflow.com/questions/8772175/how-to-implement-container-managed-transaction-cmt). – DavidS Jan 29 '15 at 18:56
  • 1
    Five months later, and I'm not certain my previous comment is true. I never tested it: I just inferred it from what I read. :-\ – DavidS Jul 06 '15 at 16:38