I know all the following rules of Java Interfaces:
Now my question is how we are creating an variable of interface EntityManager and using its methods like given code below:
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateful
public class Movies {
@PersistenceContext(unitName = "movie-unit")
private EntityManager em; // Here declaring a variable of an Interface
public void addMovie(Movie movie) throws Exception {
em.persist(movie); // Here using variable of an Interface to call its method
}
}
Please put some light on this so that I can clear up my understanding of how this code is working!
You're not creating anything here, the container is. All you've done is declare a dependency to be injected, this is how DI works in JavaEE. A very simplistic view of what is happening:
Your Movies
EJB is proxied by the container
The proxy introspects your class and discovers the annotation you've declared, along with the field you've declared it on
The container provides an instance of the EntityManager
to the proxy, which in turn makes it available to your implementation.
Presto: Instant EntityManager
. Notice how little you're involved in the process?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments